How To Remove Checked Checkbox If All Sub Check Boxes Are Unchecked?
I have group of checkboxes (Sub1,Sub2,Sub3) and One main check box. If check any sub check box the main checkbox have to be checked. If all the sub check boxes are uncheck then onl
Solution 1:
You can have a single click handler where you can check whether any of the sub items is checked
$(function() {
var $checks = $("input.user_name:not(.main)"),
$main = $('input.user_name.main');
$checks.change(function() {
$main.prop('checked', $checks.is(':checked'))
});
});
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><inputtype="checkbox"value="1"class="user_name main">Main1
<br><br><br><inputtype="checkbox"value="2"id="one"class="user_name">sub-2
<br><inputtype="checkbox"value="3"id="one"class="user_name">sub-3
<br><inputtype="checkbox"value="4"id="one"class="user_name">sub-4
<br>
Solution 2:
You can use your common user_name
class to achieve this whenever a change
event happens on them. Try this:
$('.user_name').change(function () {
var$checkbox = $(this);
var$siblings = $checkbox.siblings('.user_name');
if ($checkbox.is(':first-child')) {
$siblings.prop('checked', $checkbox.prop('checked'));
} else {
$siblings.first().prop('checked', $siblings.not(':first-child').length == $siblings.filter(':checked').length);
}
});
Also note that you have multiple elements with the same id
attribute which is invalid - the id
should be unique to an element with the document.
Solution 3:
You need to implement an OR statement. You can do it exhaustively or within a loop. This solution is of the first type:
<!DOCTYPE html><html><head><scripttype='text/javascript'src="jquery-1.10.1.js"></script><scripttype='text/javascript'>
$(window).load(function(){
var chk1 = $("input[type='checkbox'][value='1']");
var chk2 = $("input[type='checkbox'][value='2']");
var chk3 = $("input[type='checkbox'][value='3']");
var chk4 = $("input[type='checkbox'][value='4']");
chk2.on('change', function(){
chk1.prop('checked',(chk2.checked || chk3.checked || chk4.checked) );
});
chk3.on('change', function(){
chk1.prop('checked',(chk2.checked || chk3.checked || chk4.checked) );
});
chk4.on('change', function(){
chk1.prop('checked',(chk2.checked || chk3.checked || chk4.checked) );
});
});
</script></head>
...
Post a Comment for "How To Remove Checked Checkbox If All Sub Check Boxes Are Unchecked?"