【问题标题】:checkbox not working with multiple checkbox onclick复选框不适用于多个复选框onclick
【发布时间】:2019-11-09 10:26:55
【问题描述】:

function myFunction(){
  var checkBox = document.getElementById("myCheck");
  var text = document.getElementById("text");
  if (checkBox.checked == true){
    text.style.display = "block";
  } else {
    text.style.display = "none";
}}
Checkbox 1: <input type="checkbox" id="myCheck" onclick="myFunction()">

<p id="text" style="display:none">Checkbox 1 is CHECKED!</p>
<br>
Checkbox 2: <input type="checkbox" id="myCheck" onclick="myFunction()">

<p id="text" style="display:none">Checkbox 2 is CHECKED!</p>

我希望两个复选框在一个一个单击后都可以工作。 我得到的结果:只有复选框 1 工作,另一个不工作。

【问题讨论】:

    标签: javascript jquery html checkbox onclick


    【解决方案1】:

    id 属性必须是唯一的,所以在这种情况下,getElementById 只选择第一个元素。您可以将id 属性更改为class,然后使用getElementsByClassName 选择您的复选框和段落。

    Checkbox 1: <input type="checkbox" class="myCheck" onclick="myFunction()">
    
    <p class="text" style="display:none">Checkbox 1 is CHECKED!</p>
    <br>
    Checkbox 2: <input type="checkbox" class="myCheck" onclick="myFunction()">
    
    <p class="text" style="display:none">Checkbox 2 is CHECKED!</p>
    

    现在 JavaScript 部分需要识别复选框。我们应该添加一个 FOR 循环来选择 checkbox[i] 和它下面的段落。

    for (var i=0;i<checkBox.length; i++) {
        if (checkBox[i].checked == true){
        text[i].style.display = "block";
      } else {
        text[i].style.display = "none";
      }
    } 
    

    See the Demo here

    【讨论】:

      【解决方案2】:

      提供不同的 ID。它会起作用。

      function myFunction(){
        var checkBox = document.getElementById("myCheck");
        var text = document.getElementById("text");
        if (checkBox.checked == true){
          text.style.display = "block";
        } else {
          text.style.display = "none";
      }}
      
      function myFunction1(){
        var checkBox = document.getElementById("myCheck1");
        var text1 = document.getElementById("text1");
        if (checkBox.checked == true){
          text1.style.display = "block";
        } else {
          text1.style.display = "none";
      }}
      Checkbox 1: <input type="checkbox" id="myCheck" onclick="myFunction()">
      
      <p id="text" style="display:none">Checkbox 1 is CHECKED!</p>
      <br>
      Checkbox 2: <input type="checkbox" id="myCheck1" onclick="myFunction1()">
      
      <p id="text1" style="display:none">Checkbox 2 is CHECKED!</p>

      【讨论】:

      • 如果它适合您,请投票并接受答案。
      • 无法投票 --> 感谢您的反馈!声望低于 15 人的投票将被记录,但不会更改公开显示的帖子得分。
      猜你喜欢
      • 2012-09-08
      • 2022-01-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-12
      • 2013-06-18
      • 1970-01-01
      相关资源
      最近更新 更多