我正在根据我从后端获取的值动态创建复选框和相应的ID,如图所示。
创建后,如何检索此选中复选框的值?
HTML:
<tr>
<td class="valueleft">All</td>
<td class="valueleft"><input type='checkbox' id="cb1"/></td>
</tr>
<tr>
<td class="valueleft">--------</td>
<td class="valueleft">----checkbox-------</td>
</tr>
jQuery的:
$("#myTable").last().append("<tr><td>"+name+"</td><td><input type='checkbox'id="+id+"/></td></tr>");
答案 0 :(得分:3)
要检索已检查的复选框的值,您可以执行以下操作:
var checkedValues = [];
$('input[type=checkbox]:checked').each(function(){
//here this refers to the checkbox you are iterating on
checkedValues.push($(this).val());
});
或者如果你想要名字/数值对,你可以这样做:
var checkedValues = {};
$('input[type=checkbox]:checked').each(function(){
//here this refers to the checkbox you are iterating on
checkedValues[$(this).attr('id')] = $(this).val();
});
//you end up with an object with the id's as properties and the relative values as values
答案 1 :(得分:0)
你也可以使用.map:
var checkedVals = $('input:checkbox:checked').map(function(){
return $(this).val();
}).get();