How to check or uncheck a checkbox or radio using Jquery?

Dung Do Tien May 14 2020 494

I have a form update profile of a user with two information are gender and hobbies. Now I want auto-set check or uncheck any option from two these controls. 

<div class="item">
 <p>Gender</p>
 <div class="control">
    <input type="radio" name="gender" id="male" /> 
    <lable for="male">Male</lable>
    <input type="radio" name="gender" id="female" /> 
    <lable for="female">Female</lable>
    <input type="radio" name="gender" id="other" /> 
    <lable for="other">Other</lable>
 </div>
</div>

<div class="item">
 <p>Hobbies</p>
 <div class="control">
    <input type="checkbox" name="hobbies" id="movies" /> 
    <lable for="movies">Movies</lable>
    <input type="checkbox" name="hobbies" id="travel" /> 
    <lable for="travel">Travel</lable>
    <input type="checkbox" name="hobbies" id="boxing" /> 
    <lable for="boxing">Boxing</lable>
    <input type="checkbox" name="hobbies" id="fishing" /> 
    <lable for="fishing">Fishing</lable>
    <input type="checkbox" name="hobbies" id="other" /> 
    <lable for="other">Other</lable>
 </div>
</div>

I am using the latest Jquery version. Thank you for any suggestions.

Have 1 answer(s) found.
  • S

    Sandeep Kumar May 14 2020

    To check or uncheck a checkbox or radio button,  Jquery support some method for you resolved this problem. You can use attr() or prop() methods to do. Notice two methods can check and uncheck for both radio and checkbox buttons.

    1. To set checked a radio or checkbox button.

    $( "#male").prop( "checked", true); 
    

    OR

     $( "#male").attr( "checked", true); 
    

    2. To unchecked a radio or checkbox button.

     $( "#male").prop( "checked", false ); 

    Same as checked a radio or checkbox, you only set true to a false value to uncheck it.

    You also use javascript to check or uncheck a radio & checkbox button:

     document.getElementById("male").checked = true; 

    I hope these answers helpful to you.

Leave An Answer
* NOTE: You need Login before leave an answer

* Type maximum 2000 characters.

* All comments have to wait approved before display.

* Please polite comment and respect questions and answers of others.

Popular Tips

X Close