复选框计数,金额已选中/未选中

时间:2015-04-18 04:39:05

标签: javascript html5

如何显示已检查的复选框的数量?我需要显示一系列已检查的复选框,并自动更新给定组。如果我需要,我不知道如何设置数组的值来做到这一点。我也试图使用checked属性,但这也不起作用。

var infoArray = new Array();

function userSelection(userInput) {
  var itemName = userInput.name;
  var itemName2 = userInput.value;

  switch (itemName) {
    case "sectionR":
      {
        switch (itemName2) {
          case "repair car":
            infoArray[0] = 1;
            break;

          case "wood work":
            infoArray[0] = 1;
            break;

          case "explore forest":
            infoArray[0] = 1;
            //end of case "sectionR"
        }
        //end of sub switch
      }
      break;

    case "sectionA":
      {
        switch (itemName2) {
          case "clothing design":
            infoArray[1] = 1;
            break;

          case "public singing":
            infoArray[1] = 1;
            break;

          case "decorate":
            infoArray[1] = 1;
            //end of sub switch
        }
        // end of case sectionA
      }
      //end of main switch
  }
  var userOutput = new Array();
  for (var i = 0; i < itemName.length; i++) {
    userOutput.push(itemName[i].checked);
  }

  document.getElementById("selectionTotal").innerHTML = "R SECTION" + "&nbsp" + "," + "&nbspA SECTION" + "<br>" +
    infoArray;

  //end of userSelection() 
}

2 个答案:

答案 0 :(得分:2)

不是在每个复选框上放置一个onclick侦听器,而是可以在父元素上放置一个onchange侦听器,当事件冒泡时,处理该事件。

&#13;
&#13;
function update() { 
  document.getElementById('count').innerHTML =
      document.querySelectorAll('#checkboxes input[type="checkbox"]:checked').length
}
&#13;
<div id='checkboxes' onchange='update()'>
  <input type='checkbox'>A
  <input type='checkbox'>B
  <input type='checkbox'>C
  <input type='checkbox'>D
</div>
<div id='count'></div>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

查看HTML会很有帮助,但您应该能够使用document.querySelectorAll("input:checked").length来获取包含所有已检查输入元素的NodeList的长度。

以下是其工作原理的简单示例:

function checkThis() {
    var numberChecked = document.querySelectorAll('input:checked').length;
    document.getElementById('counter').innerHTML = "Number of checked boxes: " + numberChecked;
}
<form>
    <input type="checkbox" name="checkthis" onclick="checkThis()" />
    <br />
    <input type="checkbox" name="checkthis" onclick="checkThis()" />
    <br />
    <input type="checkbox" name="checkthis" onclick="checkThis()" />
    <br />
    <input type="checkbox" name="checkthis" onclick="checkThis()" />
    <br />
    <input type="checkbox" name="checkthis" onclick="checkThis()" />
    <br />
    <input type="checkbox" name="checkthis" onclick="checkThis()" />
    <br />
    <input type="checkbox" name="checkthis" onclick="checkThis()" />
    <br />
    <p id="counter">Number of checked boxes: 0</p>
</form>

如果您需要定位特定的复选框,则可以通过添加类或ID(input#id:checked)在选择器中获得更具体的信息。