如何使用带有一个按钮的jQuery选择/取消选择所有复选框?

Cow*_*der 0 html javascript checkbox jquery button

我想使用单击按钮在选择特定div /表中的所有复选框和取消选中所有复选框之间切换.此外,我希望链接/或按钮将名称更改为"全选"和"取消全选".我已经看到类似的答案使用复选框或两个不同的按钮点击,但没有这个.我会使用jquery保持简单和简短.

HTML

<body>
<div id="main">
<div id="first">
<h1>Check & Uncheck All Options</h1>
<p>Check & Uncheck All Options by Button</p>
<input id="checkAll" type="button" value="Check/Uncheck All ">
<div class="button">
<input class="first" id="Item 1" name="option1" type="checkbox">
<label class="label1" for="Item 1">Item 1</label>
<input class="first" id="Item 2" name="option1" type="checkbox">
<label class="label1" for="Item 2">Item 2</label>
<input class="first" id="Item 3" name="option1" type="checkbox">
<label class="label1" for="Item 3">Item 3</label>
<input class="first" id="Item 4" name="option1" type="checkbox">
<label class="label1" for="Item 4">Item 4</label>
</div>
</body>
Run Code Online (Sandbox Code Playgroud)

小智 5

这样怎么样:

$(function() {
  
  $(document).on('click', '#checkAll', function() {
  
    if ($(this).val() == 'Check All') {
      $('.button input').prop('checked', true);
      $(this).val('Uncheck All');
    } else {
      $('.button input').prop('checked', false);
      $(this).val('Check All');
    }
  });
  
});
Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<body>
  <div id="main">
    <div id="first">
      <h1>Check & Uncheck All Options</h1>
      <p>Check & Uncheck All Options by Button</p>
      <input id="checkAll" type="button" value="Check All">
      <div class="button">
        <input class="first" id="Item 1" name="option1" type="checkbox">
        <label class="label1" for="Item 1">Item 1</label>
        <input class="first" id="Item 2" name="option1" type="checkbox">
        <label class="label1" for="Item 2">Item 2</label>
        <input class="first" id="Item 3" name="option1" type="checkbox">
        <label class="label1" for="Item 3">Item 3</label>
        <input class="first" id="Item 4" name="option1" type="checkbox">
        <label class="label1" for="Item 4">Item 4</label>
      </div>
</body>
Run Code Online (Sandbox Code Playgroud)