use*_*900 1 html javascript checkbox jquery
我正在尝试检查一个复选框(检查列表中的所有其他复选框,并取消选中列表中的一个未选中.现在只有第一个我的意思是一个复选框检查列表中的所有剩余复选框正在发生,但反之亦然我即使未经检查的列表中的一个不起作用,也意味着取消选中.我怎样才能实现这一目标?
<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>
Run Code Online (Sandbox Code Playgroud)
我会这样做:
$('.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');
});Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<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>Run Code Online (Sandbox Code Playgroud)
编辑:根据A. Wolff的建议进行交换e.isTrigger,如下所示.e.originalEvent === undefined