Javascript计算从多个选择中选择的数量

时间:2017-08-01 13:14:49

标签: javascript html select options

这是HTML:



<select class="form-control selectVitrat" name="PVSuperior" id="PVSuperior">
      <option value="NO">NU</option>
      <option value="YES">DA</option>
    </select>
<select class="form-control selectVitrat" name="PVIntermediar9" id="PVIntermediar9">
      <option value="NO">NU</option>
      <option value="YES">DA</option>
    </select>
<select class="form-control selectVitrat" name="PVIntermediar8" id="PVIntermediar8">
      <option value="NO">NU</option>
      <option value="YES">DA</option>
    </select>
&#13;
&#13;
&#13;

如何计算从多个选择中选择的是多少?

1 个答案:

答案 0 :(得分:2)

在JavaScript中,您可以使用getElementsByTagName获取所有select。使用for循环,您可以检查有多少select具有YES值:

&#13;
&#13;
function checkTotalYes() {
  var selectElements = document.getElementsByTagName("select");
  var count = 0;
  for (var i = 0; i < selectElements.length; i++) {
    if (selectElements[i].value == 'YES')
      count++;
  }
  console.log('Total Yes: ' + count);
}

checkTotalYes();
&#13;
<select class="form-control selectVitrat" name="PVSuperior" id="PVSuperior" onchange="checkTotalYes()">
  <option value="NO">NU</option>
  <option value="YES">DA</option>
</select>
<select class="form-control selectVitrat" name="PVIntermediar9" id="PVIntermediar9" onchange="checkTotalYes()">
  <option value="NO">NU</option>
  <option value="YES">DA</option>
</select>
<select class="form-control selectVitrat" name="PVIntermediar8" id="PVIntermediar8" onchange="checkTotalYes()">
  <option value="NO">NU</option>
  <option value="YES">DA</option>
</select>
&#13;
&#13;
&#13;