CowboyCoder CowboyCoder - 3 months ago 7
HTML Question

How to Select / Deselect All Checkboxes using jQuery with a one Button?

I would like to to use a single button click to toggle between selecting all check boxes within a particular div/table and deselecting all check boxes. In addition i wanted the link/or button to change names to 'Select All' & ' deselect All'. I've seen similar answers using check boxes or two different button clicks but nothing for this. I would to keep it simple and short using 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>




Answer

How about like this:

$(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');
    }
  });
  
});
<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>

Comments