【问题标题】:Use radio button name twice使用单选按钮名称两次
【发布时间】:2020-05-24 08:52:44
【问题描述】:

我有一个包含 3 个不同“页面”的多步骤表单。 1 和 2 用于常规用户输入,第 3 页是 1 和 2 的摘要。第 1 页有一些单选按钮。我想再次在第 3 页显示这些(它们应该是可编辑的)。我不想使用不同的名称,因为它们显示完全相同......我怎样才能做到这一点?这是更好理解的代码。

input {
  display: none;
}

label {
  width: 25px;
  height: 25px;
  display: inline-block;
  color: #fff;
  background-color: #000;
  text-align: center;
  line-height: 25px;
}

input:checked + label {
  background-color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="page-1">
  <input type="radio" id="1" name="a" value="1" checked>
  <label for="1">1</label>
  <input type="radio" id="2" name="a" value="2">
  <label for="2">2</label>
</div>
<div class="page-2">
  <!-- ... -->
</div>
<div class="page-3">
  <input type="radio" id="1" name="a" value="1">
  <label for="1">1</label>
  <input type="radio" id="2" name="a" value="2">
  <label for="2">2</label>
</div>

【问题讨论】:

  • name属性可以使用相同的值,id不能使用,

标签: html css forms radio-button label


【解决方案1】:

您不能使用两次相同的id为了避免样式问题,您不应该使用数字作为属性值的首字母(来自旧规范)请参阅:What are valid values for the id attribute in HTML?

这是一个示例,允许多个 label 使用单个 input。标签需要在输入的同胞中才能设置样式。

输入的 div 兄弟的可能工作示例:

input {
  display: none;
}

label {
  width: 25px;
  height: 25px;
  display: inline-block;
  color: #fff;
  background-color: #000;
  text-align: center;
  line-height: 25px;
}

input#a1:checked ~ div label[for="a1"],
input#a2:checked ~ div label[for="a2"]{
  background-color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  <input type="radio" id="a1" name="a" value="1" checked>
  <input type="radio" id="a2" name="a" value="2">
<div class="page-1">
  <label for="a1">1</label>
  <label for="a2">2</label>
</div>

<div class="page-2">
  <!-- ... -->
</div>

<div class="page-3">
  <label for="a1">1</label>
  <label for="a2">2</label>
</div>

【讨论】:

  • 一个问题:你知道为什么this 不起作用吗?
  • @xif80599 如我的回答中所述:另外,为了避免样式问题,您不应使用数字作为属性值的首字母(旧规范)。 在 id 前面添加一个字母,就像我在 sn-p 中所做的那样;)见stackoverflow.com/questions/70579/…
【解决方案2】:

每次使用不同的id=''

  <div class="page-3">
      <input type="radio" id="3" name="a" value="1">
      <label for="1">1</label>
      <input type="radio" id="4" name="a" value="2">
      <label for="2">2</label>
    </div>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-15
    • 1970-01-01
    • 2013-03-16
    • 2017-11-14
    • 2017-12-09
    相关资源
    最近更新 更多