【问题标题】:Why can I check multiple radio buttons?为什么我可以检查多个单选按钮?
【发布时间】:2018-09-22 17:17:46
【问题描述】:

我有一个带有单选按钮的 HTML 表单,并且可以选择多个,但为什么呢?我无法自拔。

这是我的 HTML:

<input type="radio" name="nameA" id="nameA" value="nameA">
<label for="nameA">Choice A</label>
<input type="radio" name="nameB" id="nameB" value="nameB">
<label for="nameB">Choice B</label>

对于任何发现此问题的人:解决方案是给他们相同的名称

<input type="radio" name="sameName" id="nameA" value="nameA">
<label for="nameA">Choice A</label>
<input type="radio" name="sameName" id="nameB" value="nameB">
<label for="nameB">Choice B</label>

【问题讨论】:

  • 为每个单选按钮赋予相同的名称。

标签: html forms radio-button


【解决方案1】:

每当您创建单选按钮时(目的是 确保用户只能选择 1 个选项),请确保 使 name 属性的值相同

请像这样更新您的代码:

<input type="radio" name="sameName" id="nameA" value="nameA">
<label for="nameA">Choice A</label>
<input type="radio" name="sameName" id="nameB" value="nameB">
<label for="nameB">Choice B</label>

【讨论】:

    【解决方案2】:

    所有同名并且是相同形式的控件的单选按钮都是一个组的一部分。

    只能选中一个组中的一个单选按钮。

    您有两个名称不同的单选按钮。这意味着您有两个单选组,每个组包含一个单选按钮。

    如果您只想选择其中一个,则需要将它们放在同一个组中(通过让它们共享一个名称)。

    (它们仍应具有唯一的 id(因此您可以给每个人一个标签)和值(这是您在将表单提交到服务器时确定检查哪一个的方式)。

    <form>
      <fieldset>
        <legend>Thing that is being chosen</legend>
    
        <input type="radio" name="name" id="nameA" value="nameA">
        <label for="nameA">Choice A</label>
    
        <input type="radio" name="name" id="nameB" value="nameB">
        <label for="nameB">Choice B</label>
    
      </fieldset>
    </form>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-05-04
      • 2020-01-15
      • 2020-07-06
      • 2017-02-21
      • 1970-01-01
      • 2020-10-05
      • 2017-10-30
      • 2015-03-09
      相关资源
      最近更新 更多