如何使用js获取选定的单选按钮值

2022-01-21 00:00:00 radio-button javascript

我正在使用此代码来获取当前选定单选按钮的值,但它不起作用.

I am using this code to get the value of currently selected radio button, but it doesn't work.

var mailcopy = document.getElementById('mailCopy').value; 

如何使用 Javascript 获取当前选中的单选按钮值?

How to get the currently selected radio button value using Javascript?

推荐答案

HTML

<p>Gender</p>
<input type="radio" id="gender0" name="gender" value="Male">Male<br>
<input type="radio" id="gender1" name="gender" value="Female">Female<br>

JS

var gender = document.querySelector('input[name = "gender"]:checked').value;
document.writeln("You entered " + gender + " for your gender<br>");

相关文章