[SOLVED] check the limited checkbox on single click using jQuery

Issue

This Content is from Stack Overflow. Question asked by Shazia Tasneem

I want to check the limited checkboxes on single click using jquery or javascript. for example if we have 5 checkboxes but on clicking select 3 it should select only 3 checkboxes out of 5 automatically.



Solution

This is what you are looking for:

let items = $("input[name=chkBox]");

      $("#selectAllChkBox").change(function (e) {
        if ($("#selectAllChkBox").is(':checked')) {
          for (let i = 0; i < 3; i++) {
            $(items[i]).prop('checked', true);
          }
        } else {
          $("input[name=chkBox]").prop('checked', false);
        }
      });

      $(items).change(function (e) {
        let current_item = e.target;

        let checked_items = $("input[name=chkBox]:checked");
        if (checked_items.length > 3) {
          alert('You can only select three items!');
          $(this).prop('checked', false);
        }
      });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="example" class="table table-striped table-bordered table-hover table-responsive display" width="100%" cellspacing="0">
      <thead>
        <tr>
          <th>Animal</th>
          <th class="vertalign">Select 3 <input type="checkbox" class="checkbox-inline" name="selectAllChkBox" id="selectAllChkBox">
        </tr>
      </thead>
      <tbody>
        <tr>
          <td>Cat</td>
          <td class="vertalign" rowspan="5"><input class="checkbox-inline" type="checkbox" value="cat" name="chkBox"></td>
        </tr>
        <tr>
          <td>Dog</td>
          <td class="vertalign" rowspan="5"><input class="checkbox-inline" type="checkbox" value="dog" name="chkBox"></td>
        </tr>
        <tr>
          <td>Cow</td>
          <td class="vertalign" rowspan="5"><input class="checkbox-inline" type="checkbox" value="cow" name="chkBox"></td>
        </tr>
        <tr>
          <td>Mouse</td>
          <td class="vertalign" rowspan="5"><input class="checkbox-inline" type="checkbox" value="mouse" name="chkBox"></td>
        </tr>
        <tr>
          <td>Goat</td>
          <td class="vertalign" rowspan="5"><input class="checkbox-inline" type="checkbox" value="goat" name="chkBox"></td>
        </tr>

      </tbody>
    </table>


This Question was asked in StackOverflow by Mohsina and Answered by DCodeMania It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?