javascript复选框取消检查不起作用

时间:2014-06-11 21:25:45

标签: javascript jquery html checkbox

我在这个javascript代码中遇到了问题。此代码显示多个选中的值,但是当我取消选中任何值时,它会从结果中删除所有值。我想从结果中仅删除特定的未经检查的值。请任何人帮助我。

<script>

 window.addEventListener('DOMContentLoaded', function (event) {
     var boxes = document.querySelectorAll('#the_form input[type="checkbox"]'),
         area = document.getElementById('text'), i;

     for (i = 0; i < boxes.length; i += 1) {
         boxes[i].addEventListener('change', function (event) {
             var e = event.target;
             if (e.checked) {
                 area.value += e.value + '\n',' ';
             } else {
                 area.value ="";
             }
         }, false);
     } }, false);

 </script> 

HTML

<form action='search1.php' method='GET' id="the_form">
</br>

  <tr>
    <h2>Select your problem</h2> <b>Do you have difficulty in sleeping?</b>    
    <input type="checkbox" id='check1'  value="Difficulty sleeping">YES/NO<br>
 <b>Do you feel dizziness?</b>
     <input type="checkbox" id='check1'  value="Dizziness ">YES/NO<br> 
    <b>Do you feel fever?</b>
    <input type="checkbox" id='check1' onClick='check()' value='Fever'>YES/NO<br> 
    <b>Do you have headache?</b> 
    <input type="checkbox" id='check1' onClick='check()' value='Headache '>YES/NO<br> 
    <b>Do you feel warm to touch?</b> 
    <input type="checkbox" id='check1' onClick='check()' value='Warm to touch'>YES/NO<br> 
    <b>Do you have itching or burning issue?</b> 
    <input type="checkbox" id='check1' onClick='check()' value='Itching or burning'>YES/NO<br> 
    <b>Do you have bleeding issue?</b> 
    <input type="checkbox" id='check1' onClick='check()' value='Bleeding '>YES/NO<br> <br> 
    <input type='text'id="text" size='100' name='search' ></br></br> 
  </tr> 

  <input type='submit' name='submit' value='Search' ></br></br></br>

</form>

1 个答案:

答案 0 :(得分:0)

问题是,每当遇到未经检查的框时,您都会设置area.value = "",因此会删除之前框中的所有值。您应该在循环之前将值初始化为空字符串,然后仅添加选中的值。

您还必须遍历事件处理程序中的所有复选框,而不仅仅是您单击的复选框,以便获取所有选中的值。

window.addEventListener('DOMContentLoaded', function (event) {
    var boxes = document.querySelectorAll('#the_form input[type="checkbox"]'),
    area = document.getElementById('text'), i;
    for (var i = 0; i < boxes.length; i += 1) {
        boxes[i].addEventListener('change', function (event) {
            area.value = "";
            for (var j = 0; j < boxes.length; j++) {
                if (boxes[j].checked) {
                    area.value += boxes[j].value + '\n';
                }
            }
        }, false);
    } 
}, false);

DEMO