<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
</head>
<body>
<label><input type="checkbox" name="sample" class="selectall"/> Select all</label>
<div id="checkboxlist">
<label><input type="checkbox" name="sample"/>checkbox1</label><br/>
<label><input type="checkbox" name="sample"/>checkbox2</label><br />
<label><input type="checkbox" name="sample"/>checkbox3</label><br />
<label><input type="checkbox" name="sample"/>checkbox4</label><br />
</div>
<script>
$('.selectall').on('change', function(e) {
var $inputs = $('#checkboxlist input[type=checkbox]');
if(e.originalEvent === undefined) {
var allChecked = true;
$inputs.each(function(){
allChecked = allChecked && this.checked;
});
this.checked = allChecked;
} else {
$inputs.prop('checked', this.checked);
}
});
$('#checkboxlist input[type=checkbox]').on('change', function(){
$('.selectall').trigger('change');
});
</script>
</body>
</html>