Jquery traverses the checkbox to get the value of the selected item


Source:


jQuery(function($){
$("input[name='key']:checkbox").click(function(){
var ids = '';
var flag = 0;
$("#ids").attr("value",ids);
$("input[name='key']:checkbox").each(function(){
if (true == $(this).attr("checked")) {
ids += $(this).attr('value')+',';
flag += 1;
}
});
if(0 < flag) {
$("#ids").attr("value",ids);
return true;
}else {
alert(' Please choose at least one item! ');
return false;
}
});
});

This source function:

Gets the value of the checkbox name= ‘key’ and writes the value of the selected item to the hidden field < Input type=“hidden” name=“ids” id=“ids” value="" /> In the form.

Core statement:


$("input[name='key']:checkbox").each(function(){
if (true == $(this).attr("checked")) {
ids += $(this).attr('value')+',';
}
});

In HTML, if a check box is checked, the corresponding tag is checked=“checked”. However, if you use jquery alert($(“#id”).attr(“checked”)), it will tell you that you are “true” instead of “checked”, so if(“checked”==$(“#id”).attr(“checked”)) is wrong, you should write as above: if(true ==$(“#id”).attr(“checked”))