In in aspx page, there is a grid view, that has template control for checkbox, something like this
<asp:gridview .....
<columns>
<asp:TemplateField>
<HeaderTemplate>
<asp:CheckBox ID="chkAll" runat="server"/>
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox ID="chkSelect" runat="server"/>
</ItemTemplate>
</asp:TemplateField>
...
Now if I write something like
$(#'<%=chkSelect.ClientID%>').something( function() {});
I get an error saying ‘chkSelect doesn’t exists in current context, which is pretty obvious, because this element will exist when griddata is loaded, what I have done is bind the change events of the checkbox to a delegate..
$("body").delegate(":checkbox", "change", function () {
custList = $(':checkbox:checked').map(function () { return $(this).closest('tr').find('.grdCustName').text() }).get();
$('#<%=hdnFromCustomer.ClientID %>').val(custList);
}
which is again working as it should, the problem is I need to know if a checkbox with a particular id (for ex here, chkAll) is changed(clicked), then select all checkbox, checking all in not an issue, I can do this with something like $(':checkbox').attr(checked, 'on') or something.
But the problem is, if I write
$('#<%=chkAll.ClientID %>'), it doesn’t allows me to, because this checkbox isn’t present in DOM at time of start, but will be available when user clicks showReport button and grid is populated.
So, basically, my question is how can I select, or what selector should I use to select this checkbox (or any other element) in DOM that doesn’t exist but will exist at some time in future?
EDIT: In response to some answers, the problem is not binding, I HAVE DONE SO by using delegate(), which I also could have done by using .on() or .live(). The problem is as as Felix Kling commented, he hit the nail on the head, (read his comment(s) and my reply to him). The problem is the element doesn’t exists in the DOM at page startup time. It is build dynamically when user clicks the showReport button, and gridview is populated with data, this is where this element is created. Though I approach described by Yoeri may/may not work, I wanna know is there any possible way (by jQuery of course!) that I could select such an element as described in this case, or is my only option to look for like alternative like the one Yoeri answered?
Why not selecting the chkAll box on a custom attribute or class?
I often use an action attribute to bind event to … just to keep all things consistent and seperated from css classes (which are not for binding behaviour to it but for style 😉
As for adding an action attribute, you can look here … (to avoid adding an extra span element)
adding-custom-attributes-to-an-aspcheckbox-control