frosty
frosty

Reputation: 2649

Using javascript to check a radio button by it's value

There is 3 radio buttons on a website, and I want to use javascript to check the radio button that says "female". How would I do that?

<input type="radio" name="gender" value="male"> Male<br>
<input type="radio" name="gender" value="female"> Female<br>
<input type="radio" name="gender" value="other"> Other

document.getElementsByValue("female").checked = true;

Upvotes: 0

Views: 209

Answers (2)

Rahul Rana
Rahul Rana

Reputation: 455

You can get value by binding this to function and accessing the boolean value with .checked and .name which value is checked

function radionButtonChecked(e) {
  console.log(e.checked, "  ",e.value);
}
<input type="radio" name="gender" value="male" onclick="radionButtonChecked(this)"> Male<br>
<input type="radio" name="gender" value="female" onclick="radionButtonChecked(this)"> Female<br>
<input type="radio" name="gender" value="other" onclick="radionButtonChecked(this)"> Other

Upvotes: 0

Daniel Doblado
Daniel Doblado

Reputation: 2848

With document.querySelector("input[value='female']" you can select it with the value.

document.querySelector("input[value='female']").click()
<input type="radio" name="gender" value="male"> Male<br>
<input type="radio" name="gender" value="female"> Female<br>
<input type="radio" name="gender" value="other"> Other

Upvotes: 1

Related Questions