Skip to content

Instantly share code, notes, and snippets.

@baikaresandip
Created July 11, 2019 12:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save baikaresandip/f3e5403383b844eac59b81b9c75aa2a0 to your computer and use it in GitHub Desktop.
Save baikaresandip/f3e5403383b844eac59b81b9c75aa2a0 to your computer and use it in GitHub Desktop.
Check Multiple checkboxes dynamically by ID and classes. You can use this function for multiple times in a single code for different purposes
<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8'>
<meta http-equiv='X-UA-Compatible' content='IE=edge'>
<title>Check all Checkboxes</title>
<meta name='viewport' content='width=device-width, initial-scale=1'>
<script src='script.js'></script>
</head>
<body>
<label>
<input id="id_all_users" name="users" type="checkbox" />
Select all users
</label>
<ul>
<li><input class="user" name="users" type="checkbox" value="1" /> 1 </li>
<li><input class="user" name="users" type="checkbox" value="2" /> 2 </li>
<li><input class="user" name="users" type="checkbox" value="3" /> 3 </li>
<li><input class="user" name="users" type="checkbox" value="4" /> 4 </li>
<li><input class="user" name="users" type="checkbox" value="5" /> 5 </li>
</ul>
</body>
</html>
/**
* Check All checkboxes if we marked to check all
*
* @param {*} checkboxId
* @param {*} checkboxesClass
*/
function check_all ( checkboxId = '', checkboxesClass = '' ) {
$('#' + checkboxId).change(function() {
var checkboxes = $('.' + checkboxesClass);
if (!$(this).is(':checked')) {
checkboxes.each(function(){
if ($(this).is(':checked')) {
$(this).click();
}
});
} else {
checkboxes.each(function(){
if (!$(this).is(':checked')) {
$(this).click();
}
});
}
});
uncheck_all(checkboxId, checkboxesClass);
}
/**
* Uncheck main select if any one checkbox is unchecked
*
* @param {*} checkboxId
* @param {*} checkboxesClass
*/
function uncheck_all( checkboxId = '', checkboxesClass = '' ) {
$('.' + checkboxesClass).change(function() {
var checkboxes = $('.' + checkboxesClass);
selectedchecks = 0;
checkboxes.each(function(){
if ($(this).is(':checked'))
selectedchecks++;
});
if( checkboxes.length == selectedchecks ){
if( !$('#'+checkboxId).is(':checked') )
$('#'+checkboxId).prop('checked', true);
}else{
if( $('#'+checkboxId).is(':checked') )
$('#'+checkboxId).prop('checked', false);
}
});
}
check_all('id_all_users', 'user');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment