Reputation: 9610
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.
// 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:
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
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