EvilDr
EvilDr

Reputation: 9610

Checkbox onclick event only fires twice

I have a table with a checkbox in the left-most column. When each row's checkbox is checked, the row changes colour to reflect this. In the table header, there is also a 'select all' checkbox.

JSFiddle Code Here

// Checks/unchecks all checkboxes ending with a particular ID string within a table
function SelectAllRows(SelectAllCheckBox, IdEndsWith) {
    var isChecked = $(SelectAllCheckBox).is(":checked");
    $(SelectAllCheckBox).closest('table').find("input[type='checkbox'][id*='" + IdEndsWith + "']").attr("checked", isChecked);
    HighlightRowsOnChecked(SelectAllCheckBox, IdEndsWith);
}

The JQuery is only tiny, but for some reason the following logic occurs:

  1. Header checkbox is checked - all checkboxes in table successfully are checked and rows are coloured
  2. Header checkbox is then unchecked - all checkboxes become unchecked and row colouring clears
  3. Header checkbox is checked - no response!

Could somebody please help perfect this code to iron out this weird behaviour? Many thanks.

An explanation would also be appreciated as my head is spinning!

Upvotes: 0

Views: 146

Answers (1)

emerson.marini
emerson.marini

Reputation: 9348

You should use .prop() instead of .attr() in this case:

$(SelectAllCheckBox).closest('table')
    .find("input[type='checkbox'][id*='" + IdEndsWith + "']")
    .prop("checked", isChecked);

Attributes vs. Properties

The difference between attributes and properties can be important in specific situations. Before jQuery 1.6, the .attr() method sometimes took property values into account when retrieving some attributes, which could cause inconsistent behavior. As of jQuery 1.6, the .prop() method provides a way to explicitly retrieve property values, while .attr() retrieves attributes.

Reference: http://api.jquery.com/prop/

Demo: http://jsfiddle.net/q9apt/3/

Upvotes: 2

Related Questions