如何从 Javascript 更改 HTML 单选按钮选择?

发布于 2024-08-31 08:05:16 字数 77 浏览 2 评论 0原文

我需要从 Javascript 中在表单上选择一个 HTML 单选按钮(取消选择任何先前选择的单选按钮)。

这是如何实现的?

I need to select an HTML radiobutton (deselecting any previously selected radiobutton) on my form, from within Javascript.

How is this accomplished?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

·深蓝 2024-09-07 08:05:16

如果您将一个单选按钮的“checked”属性设置为 true,则另一个同名按钮将自动取消选中。

因此,

document.getElementById('buttonX').checked = true;

如果 HTML 如下所示,将导致“buttonY”未被选中:

<input type='radio' id='buttonX' name='fred' value='X'>
<input type='radio' id='buttonY' name='fred' value='Y' checked>

编辑 请记住,“单选按钮”具有该名称,因为在旧收音机(不一定比我更老)上,电台预设按钮是机械的相互链接,以便始终按下一个按钮。摆弄按钮让它们全部松开是一种有趣但危险的消遣,因为大多数成年人不欣赏一排未按下的单选按钮整齐排列的美感。

If you set the "checked" property to true on one radio button, the other button with the same name is automatically unchecked.

Thus,

document.getElementById('buttonX').checked = true;

will cause "buttonY" to be unchecked if the HTML looks like:

<input type='radio' id='buttonX' name='fred' value='X'>
<input type='radio' id='buttonY' name='fred' value='Y' checked>

edit Remember that "radio buttons" have that name because on old radios (not necessarily older than me) the station preset buttons were mechanically inter-linked such that exactly one button was pressed at all times. Fiddling with the buttons to get them all to be un-pressed was a fun but risky pastime, as most adults didn't appreciate the aesthetic appeal of a row of un-pressed radio buttons all neatly aligned.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文