skip to Main Content

I have several checkboxes on my page. If the user clicks on the first checkbox that says 1, I want all other check boxes to be checked automatically. Below is my code:

        @for (var i = 1; i <= 10; i++)
        {

            <input onclick="checkAll" name="AreChecked" class="chkTask" type="checkbox" value="@i" /> @i



        }
    </div>``

This is the output of the checkboxes:

enter image description here

If the first checkbox that says 1 is checked then I want other checkboxes 2,3,4,5,6,7,8,9,10 to be checked. I don’t have numbers for my checkboxes, I just have characters like, but I am displaying numbers in my code for the simplicity purposes.

This is what I tried:

$("#1").click(function(){ $('input:checkbox').not(this).prop('checked', this.checked); });

3

Answers


  1. Here is the minimal example, you can cater it to your needs.

    function checkAll(event){
      var clickedElement = event.target;
      
      if (clickedElement.checked) {
        $("#1").prop("checked", true);
        $("#2").prop("checked", true);
        $("#3").prop("checked", true);
      } else {
        console.log("Checkbox is unchecked");
      }
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <input type="checkbox" onclick="checkAll(event)" id="1" />
    <input type="checkbox" onclick="checkAll(event)" id="2" />
    <input type="checkbox" onclick="checkAll(event)" id="3" />
    Login or Signup to reply.
  2. I don’t know how to do it with jquery, I have done it this way

    <input onclick="checkAll()" type="checkbox" name="test" id="">
    <input type="checkbox" name="test" id="">
    <input type="checkbox" name="test" id="">
    <input type="checkbox" name="test" id="">
    <input type="checkbox" name="test" id="">
    <input type="checkbox" name="test" id="">
    <input type="checkbox" name="test" id="">
    <input type="checkbox" name="test" id="">
    
    <script>
    
    function checkAll(){
      testcheckboxes = document.getElementsByName("test");
    
      testcheckboxes.forEach(checkbox => {
        checkbox.checked = true;
      });
    
    }
    
    </script>
    
    Login or Signup to reply.
  3. Try this:

    $("#1").click(function() {
        if ($(this).is(':checked')) {
            $('input:checkbox').not(this).prop('checked', true);
        }
    });
    

    The if statement checks if the first checkbox is clicked – if true, then check all other checkboxes that are not the first checkbox.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search