在标签标签内使用时,单选按钮发生故障

时间:2013-06-06 15:17:44

标签: javascript html5 radio-button radiobuttonlist

我正在研究html和CSS。我必须在我的页面上添加5个单选按钮,并在<label>标签内添加。但是当我寻找页面时。它显示所有选中的单选按钮,我也无法取消选择它。事情是我一次只需要选择一个单选按钮。这是我的代码。

<label class="radio"><input type="radio"> Pepse</label> 
<label class="radio"><input type="radio"> Coke</label> 
<label class="radio"><input type="radio">Mirinda</label>
<label class="radio"><input type="radio">Maaza </label>

3 个答案:

答案 0 :(得分:4)

单选按钮需要一个通用名称。如果您没有为它们提供name属性,则每个单选按钮基本上都会成为单向复选框。您可以选择它们,但不能取消选择它们。

<input type="radio" name="foo" value="1" />
<input type="radio" name="foo" value="2" />

<input type="radio" value="3" />

在这种情况下,两个foo单选按钮将在内部链接,因为它们的名称相同,但值3的单选按钮将完全独立并充当您的。

答案 1 :(得分:0)

添加组名。

jsFiddle

<label class="radio"><input name="drinks" type="radio">Pepse</label>
<label class="radio"><input name="drinks" type="radio">Coke</label>
<label class="radio"><input name="drinks" type="radio">Mirinda</label>
<label class="radio"><input name="drinks" type="radio">Maaza </label>
<label class="radio"><input name="drinks" type="radio">Milk Frothers</label>

答案 2 :(得分:0)

1.无线电组需要名称,以便浏览器知道选择了哪一个

2.如果您想将标签放在输入之外,您可以使用 for 属性 告诉浏览器该标签适用于具有相同 id

的广播
<label for="a">a</label>
<input type="radio" name="aname" id="a" value="a"><br>
<label for="b">b</label>
<input type="radio" name="aname" id="b" value="b"><br>
<label for="c">c</label>
<input type="radio" name="aname" id="c" value="c"><br>
<label for="d">d</label>
<input type="radio" name="aname" id="d" value="d"><br>

但我也更喜欢标签内的无线电,所以

<label><input type="radio" name="aname" value="a">a</label><br>
<label><input type="radio" name="aname" value="b">b</label><br>
<label><input type="radio" name="aname" value="c">c</label><br>
<label><input type="radio" name="aname" value="d">d</label><br>
<label><input type="radio" name="aname" value="e">e</label><br>

3.除了使用js

之外,他们还需要一个值
<label><input type="radio" name="aname">a</label><br>
<script>
document.write(document.getElementsByTagName('label')[0].childNodes[1].nodeValue)
</script>

写一篇<br>