kevin
kevin

Reputation: 14065

jQuery check/uncheck all inside gridview

In my user control, there is a gridview. I want to select/unselect all checkboxs inside the gridview using the header checkbox. So I implement it using jQuery.

function SelectAllCheckboxes(chk) {
    $('#<%=gridView.ClientID %> >tbody >tr >td >input:checkbox').attr('checked', chk.checked);
}

In my headertemplate of the gridview I put this one

<asp:CheckBox ID="chkHeader" runat="server"  OnClick="javascript:SelectAllCheckboxes(this);"/>

It works well. But when another developer puts my user control in the aspx twice, it does not work well.

Whenever I check the 1st or the 2nd Gridview's header checkbox, only the 2nd GridViews's checkboxes are check or uncheck.

It never check the first GridView's checkboxes even when I check the 1st Gridview's header checkbox.

What kind of modification do I need ?

Thanks in advance.

Upvotes: 0

Views: 835

Answers (1)

Ivo
Ivo

Reputation: 8352

You could use closest() method:

function SelectAllCheckboxes(chk) {
    $(chk).closest('table >tbody >tr >td >input:checkbox').attr('checked', chk.checked);
}

From jquery's documentation: "Get the first element that matches the selector, beginning at the current element and progressing up through the DOM tree."

EDIT: I'm not pretty sure if it will work like that. If not, you could try:

function SelectAllCheckboxes(chk) {
    $(chk).closest('table').find('>tbody >tr >td >input:checkbox').attr('checked', chk.checked);
}

Hope it helps.

Upvotes: 3

Related Questions