找到所有选中的复选框和单选按钮

时间:2017-04-11 06:59:09

标签: javascript dom

我想找到所有选中的复选框和单选按钮。我可以这样做:

var abc = document.querySelectorAll(".some_class input[type='checkbox']:checked");

如何实时找到复选框和收音机按钮?纯粹的javascript。

1 个答案:

答案 0 :(得分:2)

如前评论,

  

" .some_class输入:选中"

样品:



function notify(){
  var els = document.querySelectorAll('input:checked');
  for(var i = 0; i< els.length; i++){
    console.log(els[i].type, els[i].value)
  }
}
&#13;
<input type="checkbox" value="1">1
<input type="checkbox" value="2">2
<input type="checkbox" value="3">3
<input type="checkbox" value="4">4
<input type="checkbox" value="5">5

<br/>

<input type="radio" name="test" value="1">1
<input type="radio" name="test" value="2">2
<input type="radio" name="test"value="3">3
<input type="radio" name="test" value="4">4
<input type="radio" name="test" value="5">5

<button onclick="notify()"> Check </button>
&#13;
&#13;
&#13;

但是如果你有复选框和收音机的不同选择器,你可以试试这个:

&#13;
&#13;
function notify(){
  var els = document.querySelectorAll('.chks input[type="checkbox"]:checked, .rbs input[type="radio"]:checked');
  for(var i = 0; i< els.length; i++){
    console.log(els[i].type, els[i].value)
  }
}
&#13;
<div class="chks">
<input type="checkbox" value="1">1
<input type="checkbox" value="2">2
<input type="checkbox" value="3">3
<input type="checkbox" value="4">4
<input type="checkbox" value="5">5
</div>

<div class="rbs">
<input type="radio" name="test" value="1">1
<input type="radio" name="test" value="2">2
<input type="radio" name="test"value="3">3
<input type="radio" name="test" value="4">4
<input type="radio" name="test" value="5">5
</div>
<button onclick="notify()"> Check </button>
&#13;
&#13;
&#13;