skip to Main Content

I have a problem, I want to validate a input type="radio" with vanilla JavaScript (probably using document.getElementById()), based on ECMAScript. How do I do it?

Here is my HTML:

<div class="gender-input">
  <input type="radio" name="gender" id="male">
  <label for="male">Male</label>
</div>

<div class="gender-input">
  <input type="radio" name="gender" id="female">
  <label for="others">Female</label>
</div>

I don’t know how to create a function to verify if the radio button is checked or not. I saw some posts talking about this, but all of them used some frameworks or another solutions, but I just want to use Vanilla JavaScript.

2

Answers


  1. Did you try something like:

    let male= document.getElementById('male').value;
    
    if(male){
    //your code
    }
    

    Or

    if(document.getElementById("male").checked = true){
    //your code
    }
    
    
    Login or Signup to reply.
  2. const value = document.querySelector("[name=gender]:checked");
    console.log(value.id);
        <div class="gender-input">
          <input type="radio" name="gender" id="male" checked />
          <label for="male">Male</label>
        </div>
    
        <div class="gender-input">
          <input type="radio" name="gender" id="female" />
          <label for="others">Female</label>
        </div>

    You can use querySelector, Becase the are same name. which one checked we can find it。 then we retrieve the id or get value

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