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;
});
});
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
//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>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.