Search code examples
c#jquerygridviewcheckboxdatakey

When checkbox checked get datagrid value using jquery


I have a checkbox template field within a gridview in c#, this field also has a hidden field with the id behind it. I want to use jQuery to raise an event on click of the checkbox to grab a datakey value so I can run a query through jQuery and add the checked item to the database. I have seen examples that get datakeys when an overall button is clicked but I want this to happen on each checkbox clicked within the gridview. I currently get "undefined" when trying to access the id.

C# within the gridview

<ItemTemplate>
     <asp:CheckBox ID="CheckBox" CssClass="checkbox" runat="server" />
     <asp:HiddenField ID="idnum" runat="server" Value='<%# Eval("id") %>' />
</ItemTemplate>

jQuery

$(document).ready(function () {
           var gridResults = document.getElementById('<%= grdResults.ClientID %>');

           $("form input:checkbox").click(function (e) {
                   var id = $(this).next('#idnum').val();
                   alert(id);
                   return false;                                        
           });
}); 

Solution

  • If there are multiple fields with ID="idnum" you should probably change that to class="idnum". After adding the class you could get the value using:

    var gridResults = $(e.target).next('.idnum').val();
    

    If idnum is just an example which is different for each field, you can just use var id = $('#idnum').val();

    EDIT: changed e.target.next('.idnum').val(); to $(e.target).next('.idnum').val(); to convert the element to jQuery object