【问题标题】:Using javascript to check a radio button by it's value使用 javascript 来检查单选按钮的值
【发布时间】:2019-01-12 02:59:42
【问题描述】:

网站上有 3 个单选按钮,我想使用 javascript 检查显示“女性”的单选按钮。我该怎么做?

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

【问题讨论】:

标签: javascript radio-button


【解决方案1】:

使用document.querySelector("input[value='female']",您可以选择它的值。

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

【讨论】:

  • 我正在使用该网站在控制台中对其进行测试,但它显示“未捕获的类型错误:无法在 :1:48 读取属性‘单击’ null”
  • 我认为您不能直接在该站点中使用控制台,但是如果您将 &lt;script&gt; document.querySelector("input[value='female']").click() &lt;/script&gt; 添加到编辑器并按运行,您可以看到它有效,我会推荐其他在线编辑器这个测试。
  • document.querySelectorAll('input[value="female"]').checked = true;似乎可以在不同网站的控制台中使用,但似乎没有选中物理单选按钮。
  • 这是一个在 JSfiddle jsfiddle.net/hwraq6Le 上工作的例子,这是一个在你的网站上工作的 gif,老实说,我不明白你在做什么不同。i.ibb.co/tztbn1Q/Peek-2019-01-12-04-29.gif
  • 没关系,你是对的。点击功能最初在 w3school 网站上不起作用,所以我切换到使用 document.querySelectorAll('input[value="female"]').checked = true 并且不起作用。现在可以使用了,谢谢。
【解决方案2】:

您可以通过将 this 绑定到函数并使用 .checked 和 .name 访问布尔值来获取值

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

【讨论】:

    猜你喜欢
    • 2014-02-05
    • 2012-12-07
    • 1970-01-01
    • 2012-03-22
    • 2017-01-05
    • 1970-01-01
    • 2021-09-03
    • 1970-01-01
    • 2013-09-07
    相关资源
    最近更新 更多