选中带有文本链接的所有复选框

Cli*_*een 2 html forms jquery

我创建了一个带有"全选"复选框的表单,该复选框选中该表单中的所有其他复选框.

我想修改它,以便select all函数将在文本链接中起作用,如下所示:

链接

<a href="#' id="checkall">Select all checkboxes</a>
Run Code Online (Sandbox Code Playgroud)

目前,它使用另一个复选框来选择所有其他复选框

形成

<form action="#" method="post" id="myform">

<fieldset>
<div class="radio"><input type="checkbox" name="checkall" id="checkall"> <label for="checkall">Check all</label></div>

<div class="radio"><input type="checkbox" name="checkbox1" id="checkbox1"> <label for="checkbox1">Checkbox</label></div>
<div class="radio"><input type="checkbox" name="checkbox2" id="checkbox2"> <label for="checkbox2">Checkbox</label></div>
<div class="radio"><input type="checkbox" name="checkbox3" id="checkbox3"> <label for="checkbox3">Checkbox</label></div>
<div class="radio"><input type="checkbox" name="checkbox4" id="checkbox4"> <label for="checkbox4">Checkbox</label></div>
<div class="radio"><input type="checkbox" name="checkbox5" id="checkbox5"> <label for="checkbox5">Checkbox</label></div>

<div class="radio"><input type="checkbox" name="checkbox6" id="checkbox6"> <label for="checkbox6">Checkbox</label></div>
<div class="radio"><input type="checkbox" name="checkbox7" id="checkbox7"> <label for="checkbox7">Checkbox</label></div>
<div class="radio"><input type="checkbox" name="checkbox8" id="checkbox8"> <label for="checkbox8">Checkbox</label></div>
<div class="radio"><input type="checkbox" name="checkbox9" id="checkbox9"> <label for="checkbox9">Checkbox</label></div>
<div class="radio"><input type="checkbox" name="checkbox10" id="checkbox10"> <label for="checkbox10">Checkbox</label></div>

</fieldset>

</form>
Run Code Online (Sandbox Code Playgroud)

脚本

<script type="text/javascript">
$(function () {
$('#checkall').click(function () {
    $('fieldset').find(':checkbox').attr('checked', this.checked);
});
});
</script>
Run Code Online (Sandbox Code Playgroud)

我已经在线查找,无法找到解决方案,任何帮助将不胜感激,谢谢

Jay*_*ena 6

你可以做这样的事情,

 $('#checkall').click(function () {
       var text=$(this).text(); 

       if (text=='Uncheck all'){
           $('fieldset').find(':checkbox').attr('checked', false);
           $(this).text('Check all');
        }else{
          $('fieldset').find(':checkbox').attr('checked', true);
          $(this).text('Uncheck all');
     }
    });
 });
Run Code Online (Sandbox Code Playgroud)


Mic*_*ior 5

将复选框更改为链接并替换this.checkedtrue如果您只想让链接始终选择所有复选框。

更新 尝试data-checked="false"在 HTML 中添加为链接的属性。那么以下应该可以解决问题:

$('#checkall').click(function () {
    var checked = $(this).data('checked');
    $('fieldset').find(':checkbox').attr('checked', !checked);
    $(this).data('checked', !checked);
});
Run Code Online (Sandbox Code Playgroud)

  • 另外,请注意,在 jQuery 1.6+ 中,设置已检查状态的正确方法是 `.prop('checked', true)` 而不是 `.attr('checked', true)`。 (2认同)