problem with checked all checkbox?
When someone clicks on first input:checkbox
, I want my code to check all checkboxes, but my code doesn't work correctly:
EXAMPLE: http://jsfiddle.net/cQYVE/
$('.table_show tr input:first').live('click',function(){
va开发者_如何学编程r isChecked = $(this).prop('checked');
$(".table_show tr input[name=checked[]]").each(function(){
if (!$(this).prop('checked') == isChecked) {
$(this).parent().click();
}
});
});
What is the cause of the problem?
the problem with your code is that you dont quote the name selector properly: change
$(".table_show tr input[name=checked[]]")
to
$(".table_show tr input[name='checked[]']")
see: http://jsfiddle.net/cQYVE/5/
also, your UX could be better. Usually when the user manually checks all the checkboxes, the checkall checkbox should become checked, and when user unchecks one box so that "all" arent checked, the checkall box should become unchecked
edit: The answer to the 2nd question is that you must maintain a count of total number of checkboxes, and when that number is checked, the checkall checkbox must be checked, otherwise it must be unchecked. do this check every time user checks a checkbox manually. Sorry, i dont have the time to provide that code right now.
Your problem is here:
$(".table_show tr input[name=checked[]]")
jQuery sees this as looking for the name checked[
, because the first ]
terminates the name.
You need to escape it with a backslash, which itself needs to be escaped with another backslash.
$(".table_show tr input[name=checked\\[\\]]")
After replacing this, your code works.
Edit: I'll leave this answer here because it works and may be useful for similar problems, but mkoryak's answer is the proper way to deal with this.
Try this one out:
http://jsfiddle.net/cQYVE/8/
$('.table_show tr').live('click',function(e) {
var wasCheckboxClicked = $(e.target).is('input[name=delete[]]'),
row = $(this),
checkBox = row.find("input:checkbox"),
shouldCheck = checkBox.prop('checked') == wasCheckboxClicked;
if (!row.is(':first-child')) {
row.css('backgroundColor', shouldCheck?"#ffd6c1":"");
checkBox.prop('checked', shouldCheck);
}
});
$('.table_show th input[type=checkbox]').live('click',function(){
if($(this).is(':checked')) {
$('.table_show td input[type=checkbox]:not(:checked)').parent().click();
}
else {
$('.table_show td input[type=checkbox]:checked').parent().click();
}
});
$('.table_show td input[type=checkbox]').live('click', function(){
if($(this).is(':checked')) {
var checkboxes = $('.table_show td input[type=checkbox]');
if(checkboxes.length == checkboxes.filter(':checked').length) {
$('.table_show th input[type=checkbox]').attr('checked', 'checked');
}
}
else {
console.log($('.table_show th input[type=checkbox]').attr('checked'));
$('.table_show th input[type=checkbox]').removeAttr('checked');
}
});
精彩评论