1

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;                                        
           });
}); 
Jason
  • 59
  • 1
  • 2
  • 10

2 Answers2

1

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

Mark
  • 15,245
  • 6
  • 95
  • 113
0

//This is the script to get datakeyname value on check box check event inside GridView

<script type="text/jscript">
        $(document).ready(function () {
            var gridResults = document.getElementById('<%= grdCateogry.ClientID %>');

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

//This is the GridView

<asp:GridView ID="grdCateogry" DataKeyNames="CategoryId" runat="server">
    <Columns>
      <asp:TemplateField HeaderText ="Try" ItemStyle-Width="20px">
         <ItemTemplate>
           <asp:CheckBox ID="chkSelect" runat="server" />   
           <asp:HiddenField ID="IDVal" runat="server" Value='<%# Eval("CategoryId") %>' />
          </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>