单选按钮无法正常工作

34

在我的网页中,我放置了一些单选按钮。但是这些按钮不能正常工作。我可以选择多个按钮。

代码:

<label for="abc" style="margin-top:-20px;margin-left:40px">xyz</label>
<input type="radio" id="abc" name="abc" >        
<label for="bcd" style="margin-top:-20px;margin-left:40px">abc</label>
<input type="radio" id="bcd" name="bcd" >
<label for="efg" style="margin-top:-20px;margin-left:40px">ccc</label>
<input type="radio" id="efg" name="efg" >

fiddle

我想只选中一个按钮,请任何人帮助我。

9个回答

85

因为你有不同的name属性值,它们应该有一个共同的name值,就像你将物品分组一样..例如

<input type="radio" name="group1" />
<input type="radio" name="group1" />
<input type="radio" name="group1" />

<!-- You can select any one from each group -->

<input type="radio" name="group2" />
<input type="radio" name="group2" />
<input type="radio" name="group2" />

演示


啊,太好了,这让我省去了很多沮丧。有时候回到基础知识是很有益的!谢谢你。 - mrClean

6
<label for="abc" style="margin-top:-20px;margin-left:40px">xyz</label>
<input type="radio" id="abc" name="abc" >        
<label for="bcd" style="margin-top:-20px;margin-left:40px">abc</label>
<input type="radio" id="bcd" name="abc" >
<label for="efg" style="margin-top:-20px;margin-left:40px">ccc</label>
<input type="radio" id="efg" name="abc" >

所有输入框必须具有相同的name属性值。

4

放在一起的单选钮必须具有相同区分大小写的name属性。

<label for="input1">First Input</label>
<input type="radio" id="input1" name="inputGroup" >
<label for="input2">Second Input</label>
<input type="radio" id="input2" name="inputGroup" >
<label for="input3">Third Input</label>
<input type="radio" id="input3" name="inputGroup" >

JSFiddle演示.

根据HTML规范:

单选按钮类似于复选框,但当多个共享同一个控件名称name时,它们是互斥的。


2

我通过搜索关键词“html单选框不起作用”找到了这个帖子。在检查了我的代码之后,我注意到我在自定义函数中使用了一个javascript方法“event.preventDefault();”,而触发此事件的HTML节点是该自定义函数中的“不起作用”的单选框父级。因此,我解决了我的问题,删除了“event.preventDefault();”。如果将来有人看到这个帖子,我希望这能在某种程度上帮助你(甚至是为了调试目的)。


1

给所有单选按钮相同的名称,以便您可以选择其中一个选项

<label for="abc" style="margin-top:-20px;margin-left:40px">xyz</label>
<input type="radio" id="abc" name="abc" >        
<label for="bcd" style="margin-top:-20px;margin-left:40px">abc</label>
<input type="radio" id="bcd" name="abc" >
<label for="efg" style="margin-top:-20px;margin-left:40px">ccc</label>
<input type="radio" id="efg" name="abc" >

现在它将正常工作。

0

name 属性指定了单选按钮属于哪个组。当你选择其中一个按钮时,同一组中的其他按钮都会被取消选择。 如果你无法确定当前按钮属于哪个组,那么每个页面上只能有一个单选按钮组。 例如:

<input type="radio" name="fruit1" value="Apple"> Apple <br>
<input type="radio" name="fruit1" value="Apricot" checked> Apricot <br>
<input type="radio" name="fruit1" value="Avocado"> Avocado
<hr>
<input type="radio" name="fruit2" value="Banana"> Banana<br>
<input type="radio" name="fruit2" value="Breadfruit"> Breadfruit<br>
<input type="radio" name="fruit2" value="Bilberry" checked>  Bilberry

0

name属性需要相同。将name分组的单选按钮放在一起以形成一个单元。


0
将它们命名为相同的方式,在您的 PHP 或接收代码中,它将类似于:
$_POST['name'] = 'value of selected radio button'

0

给予相同的属性名称。 可以使用checked属性来指示应选择哪个值。在您想要选中的值的语法中,写入checked="checked"


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接