我想获取复选框组中所有选中复选框的值。如何使用jquery从复选框组获取选中的值
<div class="checkbox-group">
<div class="checkbox">
<label for="checkbox-group-1501481486714-preview-0">
<input name="checkbox-group-1501481486714-preview[]" class="" id="checkbox-group-1501481486714-preview-0" value="physics" type="checkbox" checked="checked">physics</label>
</div>
<div class="checkbox"><label for="checkbox-group-1501481486714-preview-1"><input name="checkbox-group-1501481486714-preview[]" class="" id="checkbox-group-1501481486714-preview-1" value="math" type="checkbox">math</label>
</div>
<div class="checkbox"><label for="checkbox-group-1501481486714-preview-2">
<input name="checkbox-group-1501481486714-preview[]" class="" id="checkbox-group-1501481486714-preview-2" value="chemistry" type="checkbox">chemistry</label>
</div>
</div>
以下是脚本代码
document.getElementById('btn').addEventListener('click', function() {
$(document).ready(function(){
var x = $(".userform").find(":input");
$.each(x, function(i, field){
if(field.type == "text")
{
$("#results").append("name: "+field.name + ": " +"Value: "+ field.value +"<br>");
}
else if(field.type == "checkbox")
{
var result = $('input[type="checkbox"]:checked');
if(result.length > 0)
{
$("#results").append("this is checked "+"name: "+field.name + ": " +"Value: "+ field.value +"<br>");
}
else{
$("#results").append("this is unchecked");
}
}
});
});
});
当我把一切都取消选中则给出了这样的输出
this is unchecked
this is unchecked
this is unchecked
,但是当我检查任何它给这个输出
this is checked name: checkbox-group-1500619332922: Value: on
this is checked name: checkbox-group-1500619332922: Value: on
this is checked name: checkbox-group-1500619332922: Value: on
在此先感谢
无法正常工作。同样的问题,当我检查一个所有返回'开',但是当所有不检查,然后什么都不返回。 –
如果他们没有被检查,你想要返回什么? – madalinivascu
没什么,但如果任何人被检查想要得到它的价值,即“phy”,“math”或“phy”。 –