0

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;
1

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

8 Comments

I'm using this website to test it out in the consoles but it says "Uncaught TypeError: Cannot read property 'click' of null at <anonymous>:1:48"
I don't think you can use the console directly in that site, but if you add <script> document.querySelector("input[value='female']").click() </script> to the editor and the press run you can see that works, I would recomend other online editor for this tests.
document.querySelectorAll('input[value="female"]').checked = true; seems to work in the console on a different website, but the physical radio button doesn't seem to be checked.
This is an example working on JSfiddle jsfiddle.net/hwraq6Le and here is a gif working on your site, I honestly don't understand what you are doing differently .i.ibb.co/tztbn1Q/Peek-2019-01-12-04-29.gif
Never mind, you're right. The click function wasn't working initially on the w3school website, so I switched over to using document.querySelectorAll('input[value="female"]').checked = true and that wasn't working. It's working now, thanks.
|
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.