首页 > 解决方案 > 单选按钮不起作用 - 状态没有改变

问题描述

我正在使用一个教程,它教我如何制作自定义单选按钮。我的问题是,当我制作 3 个单选按钮时,只有第一个在工作。无法单击另外两个。当我单击另一个按钮时,只有第一个按钮起作用。

HTML:

    <label for="myRadioId" class="radio">
      <input type="radio" name="myRadioField" id="myRadioId" class="radio__input">
      <div class="radio__radio"></div>
      option 1
    </label><br>
    <label for="myRadioId" class="radio">
      <input type="radio" name="myRadioField" id="myRadioId" class="radio__input">
      <div class="radio__radio"></div>
    option 2
    </label><br>
    <label for="myRadioId" class="radio">
      <input type="radio" name="myRadioField" id="myRadioId" class="radio__input" disabled>
      <div class="radio__radio"></div>
     disabled
    </label>

CSS:

    .radio {
      cursor: pointer;
      display: inline-flex;
    }


    .radio__input {
      display: none;
    }

    .radio__radio {
      width: 1.25rem;
      height: 1.25rem;
      border: 2px solid #d8e4e2;
      border-radius: 50%;
      margin-right: 10px;
      box-sizing: border-box;
      padding: 2px;
    }

    .radio__radio::after {
      content: "";
      width: 100%;
      height: 100%;
      display: block;
      background: #009879;
      border-radius: 50%;
      transform: scale(0);
      transition: transform 0.15s;
    }

    .radio__input:checked + .radio__radio::after {
      transform: scale(1);
    }

这是它的样子,只有顶部单选按钮有效

有人知道如何使单选按钮开始工作吗?

标签: htmlcss

解决方案


  • <label>具有属性的 Afor将在单击时切换相应的复选框/单选按钮id
  • 检查时,一个单选按钮将取消选中所有其他广播按钮name
  • ID 必须是唯一的。

现在,您所有的单选按钮都具有相同的 ID。除了无效之外,这还会导致单击任何单选按钮(因为它们都在<label>with内for="myRadioId")将尝试单击带有 ID 的单选按钮myRadioId。您的第一个单选按钮匹配,因此它被点击。(其他两个也匹配并不重要,因为 ID 应该只存在一次!)

解决方案:为每个单选按钮使用不同的 ID:

<label for="myRadioId1" class="radio">
  <input type="radio" name="myRadioField" id="myRadioId1" class="radio__input">
  <div class="radio__radio"></div>
  option 1
</label><br>
<label for="myRadioId2" class="radio">
  <input type="radio" name="myRadioField" id="myRadioId2" class="radio__input">
  <div class="radio__radio"></div>
option 2
</label><br>
<label for="myRadioId3" class="radio">
  <input type="radio" name="myRadioField" id="myRadioId3" class="radio__input" disabled>
  <div class="radio__radio"></div>
 disabled
</label>

(另外,他们可能也需要一个value,这样您就可以通过查看表单数据知道最后点击了哪个。)


推荐阅读