与标题一样,我想获得使用相同名称的所有单选按钮值。这是html代码
<input type="radio" id="choice-yes-1" name="choice[0]" value="Yes" /> Yes <br/>
<input type="radio" id="choice-no-1" name="choice[0]" value="No" /> No <br />
<input type="radio" id="choice-yes-2" name="choice[1]" value="Yes" /> Yes <br />
<input type="radio" id="choice-no-2" name="choice[1]" value="No" /> No <br />
我希望javascript有点像这样
ctr = 0;
for (i=0;i<2;i++){
if(document.getElementsByName("choice")[i].value == "Yes"){
ctr++;
}
}
console.log(ctr);
我想要一些javascript,这样会产生多少肯定的选择。
答案 0 :(得分:1)
您可以使用$('input[id^=choice-][value=Yes]:checked').length
获取值为checked
的所有Yes
元素
$('input[id^=choice-][type=radio]').change(function() {
console.log($('input[id^=choice-][value=Yes]:checked').length)
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="radio" id="choice-yes-1" name="choice[0]" value="Yes" checked /> Yes <br/>
<input type="radio" id="choice-no-1" name="choice[0]" value="No" /> No <br />
<input type="radio" id="choice-yes-2" name="choice[1]" value="Yes" /> Yes <br />
<input type="radio" id="choice-no-2" name="choice[1]" value="No" /> No <br />
答案 1 :(得分:0)
document.getElementsByName("choice")
是空数组,因为没有这样的元素。
解决方案:
let result = [].filter.call(document.querySelectorAll('input[type=radio]'), function(e){
return e.value === 'Yes'
})
console.log(result.length)
答案 2 :(得分:0)
试试这个,计数会上下但不低于0
var count = 0;
$('input').change(function() {
if ($(this).val() == "Yes") {
count++
} else {
if (count == 0) {
return;
}
count--;
}
console.log(count)
})
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="radio" id="choice-yes-1" name="choice[0]" value="Yes" /> Yes
<br/>
<input type="radio" id="choice-no-1" name="choice[0]" value="No" /> No
<br />
<input type="radio" id="choice-yes-2" name="choice[1]" value="Yes" /> Yes
<br />
<input type="radio" id="choice-no-2" name="choice[1]" value="No" /> No
<br />
&#13;