我正在尝试使用jQuery选中/取消选中所有复选框。现在,通过选中/取消选中parent复选框,所有的子复选框都被选中/取消选中,同时parent复选框的文本被更改为checkall/uncheckall。
现在,我想用一个输入按钮替换父复选框,并将按钮上的文本也更改为checkall/uncheckall。THere是代码,有没有人可以修改一下代码?
$( function() {
$( '.checkAll' ).live( 'change', function() {
$( '.cb-element' ).attr( 'checked', $( this ).is( ':checked' ) ? 'checked' : '' );
$( this ).next().text( $( this ).is( ':checked' ) ? 'Uncheck All' : 'Check All' );
});
$( '.cb-element' ).live( 'change', function() {
$( '.cb-element' ).length == $( '.cb-element:checked' ).length ? $( '.checkAll' ).attr( 'checked', 'checked' ).next().text( 'Uncheck All' ) : $( '.checkAll' ).attr( 'checked', '' ).next().text( 'Check All' );
});
});
<input type="checkbox" class="checkAll" /> <b>Check All</b>
<input type="checkbox" class="cb-element" /> Checkbox 1
<input type="checkbox" class="cb-element" /> Checkbox 2
<input type="checkbox" class="cb-element" /> Checkbox 3
发布于 2011-03-08 17:46:53
试试这个:
$(document).ready(function(){
$('.check:button').toggle(function(){
$('input:checkbox').attr('checked','checked');
$(this).val('uncheck all');
},function(){
$('input:checkbox').removeAttr('checked');
$(this).val('check all');
})
})
发布于 2013-07-28 05:08:06
这是我找到的最短的方法(需要jQuery1.6+)
HTML:
<input type="checkbox" id="checkAll"/>
JS:
$("#checkAll").change(function () {
$("input:checkbox").prop('checked', $(this).prop("checked"));
});
我之所以使用.prop,是因为.attr不适用于jQuery 1.6+中的复选框,除非您显式地将一个选中属性添加到您的输入标记中。
示例:
$("#checkAll").change(function () {
$("input:checkbox").prop('checked', $(this).prop("checked"));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form action="#">
<p><label><input type="checkbox" id="checkAll"/> Check all</label></p>
<fieldset>
<legend>Loads of checkboxes</legend>
<p><label><input type="checkbox" /> Option 1</label></p>
<p><label><input type="checkbox" /> Option 2</label></p>
<p><label><input type="checkbox" /> Option 3</label></p>
<p><label><input type="checkbox" /> Option 4</label></p>
</fieldset>
</form>
发布于 2011-12-10 22:28:47
Html
<input type="checkbox" name="select_all" id="select_all" class="checkAll" />
Javascript
$('.checkAll').click(function(){
if($(this).attr('checked')){
$('input:checkbox').attr('checked',true);
}
else{
$('input:checkbox').attr('checked',false);
}
});
https://stackoverflow.com/questions/5229023
复制相似问题