skip to Main Content

enter image description hereMy goal is to set only one of the following two checkboxes to be selected at a time.
The jQuery only captures the elements of the parent layer(staffTypeSet), but cannot capture those of the child layer(.staffType2).

$('.staffType2').click(function () {
 $(".staffType2").not(this).removeAttr("checked");
 });

The JavaScript code I designed is not having any effect. What could be the reason for this problem? Do you have any solutions or ideas? Thank you.

2

Answers


  1. The correct way to uncheck a checkbox is to use the .prop() method instead of .removeAttr().

    Here’s the corrected sample code:

    $('.staffType2').click(function () {
      $(".staffType2").not(this).prop("checked", false);
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <input class="staffType2" type="checkbox" id="vehicle1" name="vehicle1" value="Bike">
    <label for="vehicle1"> I have a bike</label><br>
    <input class="staffType2" type="checkbox" id="vehicle2" name="vehicle2" value="Car">
    <label for="vehicle2"> I have a car</label><br>
    <input class="staffType2" type="checkbox" id="vehicle3" name="vehicle3" value="Boat">
    <label for="vehicle3"> I have a boat</label>

    However, if you want to allow only one checkbox to be selected at a time, I recommend using radio buttons instead. Radio buttons are designed for this purpose, and you won’t need any additional jQuery code to achieve the desired behavior.

    To use radio buttons, change the input type to radio and give them the same name attribute. For example:

    <input id="vehicle1" type="radio" class="staffType2" name="staffType" value="1">
    <label for="vehicle1"> I have a bike</label>
    <input id="vehicle2" type="radio" class="staffType2" name="staffType" value="2">
    <label for="vehicle2"> I have a car</label>

    With radio buttons, only one can be selected at a time within the group with the same name attribute.

    Login or Signup to reply.
  2. Becase prop and attribute are different.

    Use prop instead of removeAttr

    Like this example from your question

    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    
    <div>
    check boxes
    </div>
    <div>
    <input type="checkbox" id="staffType" class="staffType2">醫事人員</input>
    <input type="checkbox" id="staffType2" class="staffType2">醫生</input>
    </div>
    
    <script>
    $('.staffType2').click(function () {
     //console.log($(".staffType2").not(this));
     $(".staffType2").not(this).prop("checked", false);
     });
    </script>

    Google key word for differnece between prop and attribute =>
    attr prop jquery difference

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