【问题标题】:Jquery : specify an id of an input:checkbox elementJquery : 指定输入的 id:checkbox 元素
【发布时间】:2020-10-27 13:33:28
【问题描述】:

如果是 jquery 代码,我有这个小示例,但我想让它更具体地用于我的 HTML 页面的两个不同输入之一。

  <script>
  // check only one box at time
  $(document).ready(function() {
      $('input:checkbox').click(function() {
          $('input:checkbox').not(this).prop('checked', false);
      });
  });
  </script>

这是两个相关的输入:

<div id="reponses-section" class="form-check">
    <c:forEach items="${question.reponses}" var="reponse">
        <input id="${reponse.id}" name="id-reponse" value="${reponse.id}"
                type="checkbox" class="form-check-input">
        <h5>${reponse.texte}</h5>
    </c:forEach>
</div> 

<div id="theme-btn" class="pull-right">
    <label class="switch">
        <input id="changeThemeBtn" type="checkbox" onclick="getTheme(this);" value="dark">
        <span class="slider round"></span>
    </label>
</div>

是否可以为js代码示例指定一个id,如果可以,使用的语法是什么?

提前谢谢你

【问题讨论】:

  • 所以你正在重新创建单选按钮?

标签: javascript html jquery css input


【解决方案1】:

jQuery 使用 CSS 选择器语法选择项目,因此 ID 将只是 #yourTargetId

【讨论】:

  • // 每次只勾选一个框 $(document).ready(function() { $('.form-check-input input:checkbox').click(function() { $( '.form-check-input input:checkbox').not(this).prop('checked', false); }); });
【解决方案2】:

我强烈建议您使用此方法。您可以随意更改data-id 名称。

$(document).ready(function() {
    $('input[data-id="checkbox1"]').click(function() {
        $('input[data-id="checkbox1"]').prop('checked', false);
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

<input data-id="checkbox1" id="${reponse.id}" name="id-reponse" value="${reponse.id}" type="checkbox" class="form-check-input">

<input data-id="checkbox2" id="changeThemeBtn" type="checkbox" onclick="getTheme(this);" value="dark">

【讨论】:

  • 这行不通了...这个代码示例应该允许一次选中一个复选框...但是现在我无法检查任何人...
  • 否 @jozinho22 它仍然有效,但您不应该使用 .not(this) 和 .prop("checked", false)。因为如果你使用这些,你就不能检查这些。现在我编辑了我的帖子,请运行代码 sn-p。
猜你喜欢
  • 1970-01-01
  • 2021-11-15
  • 2015-09-22
  • 2013-05-12
  • 2012-08-11
  • 2015-12-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多