I have a table rows with checkboxes, when I click the row takes the class 'selected' and the checkbox becomes selected.
$("#emp_grid tbody tr").click(function (e) {
if (e.target.type == "checkbox") {
// stop the bubbling to prevent firing the row's click event
e.stopPropagation();
} else {
var $checkbox = $(this).find(':checkbox');
$checkbox.attr('check开发者_开发技巧ed', !$checkbox.attr('checked'));
$(this).filter(':has(:checkbox)').toggleClass('selected');
}
});
How can I make all the other checkboxes un-selected and remove the 'selected' class from rows except the selected one?
Using your current script something like this should work.
$("#emp_grid tbody tr").click(function(e) {
$("#emp_grid tbody tr").removeClass("selected");
$("#emp_grid :checkbox").not(e.target).removeAttr("checked");
if (e.target.type == "checkbox") {
// stop the bubbling to prevent firing the row's click event
e.stopPropagation();
} else {
var $checkbox = $(this).find(':checkbox');
$checkbox.attr('checked', !$checkbox.attr('checked'));
$(this).filter(':has(:checkbox)').toggleClass('selected');
}
});
Code example on jsfiddle
Not sure of the final markup, but it sounds you only want one checkbox selectable? If that is the case maybe a radio button list would be more appropriate instead of a checkbox list?
Update
To allow for toggle of checkbox on row click you can try something like this:
$("#emp_grid tbody tr").click(function(e) {
$("#emp_grid tbody tr").removeClass("selected");
var $checkbox = $(this).find(':checkbox');
$("#emp_grid :checkbox").not($checkbox).removeAttr("checked");
if (e.target.type == "checkbox") {
// stop the bubbling to prevent firing the row's click event
e.stopPropagation();
} else {
$checkbox.attr('checked', !$checkbox.attr('checked'));
$(this).filter(':has(:checkbox)').toggleClass('selected');
}
});
Updated fiddle
精彩评论