在Javascript中选中复选框时显示消息

时间:2018-03-16 03:24:05

标签: javascript jquery html checkbox

我知道它应该很简单,但是我找不到办法做到这一点,我感觉很简单,但我被卡住了。我每次选中复选框时都会尝试显示一条消息。我有下面的代码,但我只能显示第一个复选框的消息。我刚刚开始使用Javascript。



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";
    }
}

<!DOCTYPE html>
<html>
<body>

<p>Display some text when the checkbox is checked:</p>

Checkbox: <input type="checkbox" id="myCheck"  onclick="myFunction()">

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

Checkbox2: <input type="checkbox" id="myCheck"  onclick="myFunction()">

<p id="text" style="display:none">Second checkbox is checked</p>

Checkbox3: <input type="checkbox" id="myCheck"  onclick="myFunction()">

<p id="text" style="display:none">Third checkbox is checked</p>



</body>
</html>
&#13;
&#13;
&#13;

8 个答案:

答案 0 :(得分:1)

id必须是唯一的,您可以将idcheckbox p作为参数传递给函数,如下所示,

function myFunction(id,pid) {
    var checkBox = document.getElementById(id);
    var text = document.getElementById(pid);
    if (checkBox.checked == true){
        text.style.display = "block";
    } else {
       text.style.display = "none";
    }
}
<!DOCTYPE html>
<html>
<body>

<p>Display some text when the checkbox is checked:</p>

Checkbox: <input type="checkbox" id="myCheck1"  onclick="myFunction(this.id,'text1')">

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

Checkbox2: <input type="checkbox" id="myCheck2"  onclick="myFunction(this.id,'text2')">

<p id="text2" style="display:none">Second checkbox is checked</p>

Checkbox3: <input type="checkbox" id="myCheck3"  onclick="myFunction(this.id,'text3')">

<p id="text3" style="display:none">Third checkbox is checked</p>



</body>
</html>

答案 1 :(得分:1)

不会继续谈论why #IDs need to be unique的重要性以及它如何阻碍复选框的预期行为。有2个演示:

演示1 使用的JavaScript是IMO矫枉过正的简单任务。

  1. 对于事件处理,请尽量避免使用on-event attribute event handlers

    <div onclick =&#34; func();&#34; ></div>

    请尝试 addEventListener() ,请点击链接了解详情。

  2. Event Delegation用于演示1 ,因此只有添加的<form>元素用作eventListener而不是多个复选框。

  3. 引用表单控件(例如inputtextarea等)的另一种方法是使用HTMLFormControlsCollection API。将输入包装到实际的<form>标记中,并为其提供#id和/或[name]属性,我们可以使用简单的语法。在这个演示中,它确实是不需要的,但这是传统方式与事件委托/ HTMLFCC 相比的一个例子:

    正常方式:

     var chxs = document.querySelectorAll('[type=checkbox]');
     for (let i = 0; i < chxs.length; i++) {
        chxs[i].addEventListener('change', message);
     }
    

    事件委派/ HTMLFormControlsCollection

     var form = document.forms.formID;
    
     form.addEventListener('change', message);
    
       
  4. 演示2 仅使用CSS。

    • 使用两个伪类:

      • :checked为我们提供了两种状态来更改display:none/block等样式。

      • + Adjacent Sibling Combinator 允许我们对紧跟复选框的元素(以及其他兄弟姐妹和后代节点,如果需要)进行细粒度控制。

    在演示中评论的详细信息

    演示1

    &#13;
    &#13;
    // Reference the form - see HTMLFormControlsCollection
    var chxGrp = document.forms.checkGroup;
    
    /* Register the change event to form. 
    || Call message() function when a change event happens on or 
    || within the form.
    || A change event occurs when the user enters data (*input*) 
    || within a form control like an input (*focus*) then clicks onto
    || another (*unfocus*).
    || change event is different than most of the events because it
    || involves multple steps from the user, but it is very effective 
    || for form controls.
    */
    chxGrp.addEventListener('change', message);
    
    /* The Event Object is passed through, you might've seen it as 
    || "e" or "evt". How it's labelled doesn't matter because Event
    || Object is always available when you deal with the DOM.
    */
    function message(event) {
      
      // if the node clicked is a checkbox see if it's...
      if (event.target.type === 'checkbox') {
      
        // ... checked then...
        if (event.target.checked) {
        
          // ...find the node that follows it (i.e. <b>)...
          event.target.nextElementSibling.className = "message";
        } else {
          /* Otherwise remove any class on it. (there's a more modern
          || method: classList that can be used instead)
          */
          event.target.nextElementSibling.className = "";
        }
      }
      return false;
    }
    &#13;
    b {
      display: none
    }
    
    label {
      display: table
    }
    
    [type=checkbox] {
      display: table-cell;
    }
    
    .message {
      display: table-cell;
    }
    &#13;
    <!DOCTYPE html>
    <html>
    
    <head>
    </head>
    
    <body>
    <!-- Wrapped the checkboxes with a <form> giving us opportunities: 
    HTMLFormControlsCollection API for specialized referencing and
    Event Delegation allowing us to use a single eventListener for an
    unlimited amount of event.targets (clicked, changed, inputed, 
    etc. buttons, links, etc.)-->
      <form id='checkGroup'>
    
        <p>Display some text when the checkbox is checked: </p>
    
        <label>Checkbox 1: <input type="checkbox">
      <b>Checkbox is CHECKED!</b>
      </label><br>
    
        <label>Checkbox 2: <input type="checkbox">
      <b>Second checkbox is checked</b>
      </label><br>
    
        <label>Checkbox 3: <input type="checkbox">
      <b>Third checkbox is checked</b>
      </label><br>
    
      </form>
    
    </body>
    
    </html>
    &#13;
    &#13;
    &#13;

    演示2 - 仅限CSS

    &#13;
    &#13;
    /* Default state of message tag */
    
    b {
      display: none
    }
    
    
    /* Using label as a container that acts like a table */
    
    label {
      display: table
    }
    
    
    /* Checkboxes are normally set as a component that sits inline
    with their siblings. Acting as a table-cell does that and has
    additional advantages as well. 
    When the checkbox is :checked...
    The adjacent sibling + <b> behaves as a table-cell as well,
    thereby being shown/hidden by the corresponding checkbox being
    toggled.
    */
    
    [type=checkbox],
    [type=checkbox]:checked + b {
      display: table-cell;
    }
    &#13;
    <!DOCTYPE html>
    <html>
    
    <head>
    </head>
    
    <body>
      <!-- Layout has been slightly re-arranged to take advantage of 
    styling combonations and tag behavior -->
      <p>Display some text when the checkbox is checked: </p>
    
      <label>Checkbox 1: <input type="checkbox">
      <b>Checkbox is CHECKED!</b>
      </label><br>
    
      <label>Checkbox 2: <input type="checkbox">
      <b>Second checkbox is checked</b>
      </label><br>
    
      <label>Checkbox 3: <input type="checkbox">
      <b>Third checkbox is checked</b>
      </label><br>
    
    
    
    </body>
    
    </html>
    &#13;
    &#13;
    &#13;

答案 2 :(得分:0)

您有多个具有相同ID的元素。尝试更改两个ID,使其末尾有一个数字(myCheck 1或myCheck2),或者将其更改为其他内容。这是我的建议:

function myFunction(idCheck, idText) {
    var checkBox = document.getElementById(idCheck);
    var text = document.getElementById(idText);
    if (checkBox.checked == true){
        text.style.display = "block";
    } else {
       text.style.display = "none";
    }
}
<html>
<body>

<p>Display some text when the checkbox is checked:</p>

Checkbox: <input type="checkbox" id="myCheck"  onclick="myFunction('myCheck', 'text')">

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

Checkbox2: <input type="checkbox" id="myCheck1"  onclick="myFunction('myCheck1', 'text1')">

<p id="text1" style="display:none">Second checkbox is checked</p>

Checkbox3: <input type="checkbox" id="myCheck2"  onclick="myFunction('myCheck2', 'text2')">

<p id="text2" style="display:none">Third checkbox is checked</p>



</body>
</html>

答案 3 :(得分:0)

首先,您需要具有uniq id的输入类型复选框。

<input type="checkbox" id="uniq_id" />

然后在脚本中调用您的函数

$("#uniq_id").click( function(){
  if( $(this).is(':checked') ){ 
     //call your function here
     myFunction(this);  
   }
});

答案 4 :(得分:0)

id必须是唯一的。使用id

onclick传递给this.id处理程序

function myFunction(id) {
  var checkBox = document.getElementById(id);
  var text = document.getElementById("text");
  if (checkBox.checked === true) {
    text.style.display = "block";
  } else {
    text.style.display = "none";
  }
}
<p>Display some text when the checkbox is checked:</p>

Checkbox: <input type="checkbox" id="myCheck" onclick="myFunction(this.id)">

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

Checkbox2: <input type="checkbox" id="myCheck2" onclick="myFunction(this.id)">

<p id="text" style="display:none">Second checkbox is checked</p>

Checkbox3: <input type="checkbox" id="myCheck3" onclick="myFunction(this.id)">

<p id="text" style="display:none">Third checkbox is checked</p>

答案 5 :(得分:0)

好吧,因为id是唯一标识符,所以你的函数总是选择第一个复选框。

document.getElementById("myCheck");

您需要将其修改为smth。像这样

<!DOCTYPE html>
<html>
<body>

    <p>Display some text when the checkbox is checked:</p>
    Checkbox:
    <input type="checkbox" id="check_1" onclick="myFunction(event)">
    <p id="text_check_1" style="display:none">Checkbox is CHECKED!</p>

    Checkbox2:
    <input type="checkbox" id="check_2" onclick="myFunction(event)">
    <p id="text_check_2" style="display:none">Second checkbox is checked</p>

    Checkbox3:
    <input type="checkbox" id="check_3" onclick="myFunction(event)">
    <p id="text_check_3" style="display:none">Third checkbox is checked</p>

    <script>
        function myFunction(event) {
            var checkBox = event.target,
                id = checkBox.id,
                text = document.getElementById("text_" + id);
            if (checkBox.checked == true) {
                text.style.display = "block";
            } else {
                text.style.display = "none";
            }
        }
    </script>
</body>
</html>

答案 6 :(得分:0)

确实你必须使用不同的ID,你也不需要几个p元素,最后为了避免不必要的查询,你可以将点击的元素传递给函数,因为你通过{调用它{1}} attr。

onclick
function myFunction(elem) {
    var checkBox = elem;
    var p = document.getElementsByTagName('p')[1];
    if (checkBox.checked == true){
        p.innerHTML = "Checkbox <b>" + checkBox.id + "</b> is CHECKED!"
        p.style.display = "block";
    } else {
       p.style.display = "none";
    }
}

HIH

答案 7 :(得分:0)

你根本不需要javascript或jquery - 这可以单独用CSS实现 - 使用直接兄弟选择器和:checked伪选择器你可以在下一个p上设置显示或可见性属性。

您确实有多个ID,因此需要更正 - 但只需要在复选框后切换下一个p就可以使用CSS。

p{display: none}
input[type="checkbox"]:checked + p {display: block}
<p>Display some text when the checkbox is checked:</p>

Checkbox: <input type="checkbox" id="myCheck1">
<p>First Checkbox is CHECKED!</p>

Checkbox2: <input type="checkbox" id="myCheck2">

<p>Second checkbox is checked</p>

Checkbox3: <input type="checkbox" id="myCheck2">

<p>Third checkbox is checked</p>