通过 JavaScript 检查单选按钮组的值?

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

这可能看起来很愚蠢而且非常愚蠢,但我似乎无法弄清楚如何通过 JavaScript 在我的 HTML 表单中检查单选按钮组的值.我有以下代码:

This may seem silly and downright stupid but I can't seem to figure out how to check the value of a radio button group in my HTML form via JavaScript. I have the following code:

<input type="radio" id="genderm" name="gender" value="male" />
<label for="genderm">Male</label>
<input type="radio" id="genderf" name="gender" value="female" />
<label for="genderf">Female</label>

如何通过 JavaScript 检索 gender 的值?

How do I retrieve the value of gender via JavaScript?

推荐答案

如果你使用 jQuery 之类的 javascript 库,这很容易:

alert($('input[name=gender]:checked').val());

此代码将选择带有 gender 名称的 checked 输入,并获取它的 value.是不是很简单?

This code will select the checked input with gender name, and gets it's value. Simple isn't it?

现场演示

相关文章