How to get single selected from the radio button using Jquery?

Dung Do Tien Apr 10 2020 496

I want get gender from the user from a registration form with three radio buttons Male, Female and Other. But I don't know how to get value selected from three that checkboxes.

<div class="col-md-2 form">
    <div class="title">Gender</div>
    <div class="form-item">
        <input type="radio" name="gender" id="radio-1" value="1" class="custom" />
          <label for="radio-1">Male</label>
          <input type="radio" name="gender" checked id="radio-2" value="2" class="custom" />
          <label for="radio-2">Female</label>
          <input type="radio" name="gender" id="radio-3" value="3" class="custom" />
          <label for="radio-3">Other</label>
    </div>
</div>

How can I do this?

Have 1 answer(s) found.
  • S

    Sandeep Kumar Apr 12 2020

    To get value selected of a radio button in a list of radios, have many ways to do this.

    1. Using  :checked selector of Jquery (recommended).

    var gender = $(".form .form-item input[name='gender']:checked").val();
    //return gender = 2 

    See demo code

    2. Using each() loop and is() of Jquery

    var gender = "";
    $(".form .form-item input[name='gender']").each(function(){
      if($(this).is(":checked")){
    	 gender = $(this).val();
      }
    });
    
    alert(gender); 

    See demo code

    3. Using filter() method of Jquery

    var lstGender = $(".form .form-item input[name='gender']");
    var gender = lstGender.filter(":checked").val();
    alert(gender); 

    See demo code

    Still have more ways to do this. You also using js to get but it is no shortcode.

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