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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2761455/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 01:49:23  来源:igfitidea点击:

How do you change an HTML radiobutton selection from Javascript?

javascripthtmlformsradio-button

提问by Giffyguy

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

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

How is this accomplished?

这是如何实现的?

回答by Pointy

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

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

Thus,

因此,

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

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

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

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

editRemember 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.

编辑请记住,“单选按钮”有这个名字,因为在旧收音机(不一定比我更老)上,电台预设按钮是机械互连的,因此始终只按下一个按钮。摆弄按钮让它们全部被取消按下是一种有趣但有风险的消遣,因为大多数成年人并不欣赏一排整齐排列的未按下单选按钮的美感。