在多選场景中,我們往往需要收集所有被勾選的複選框的值。下面通過一段源碼來說明如何實現,並附上關鍵注意事項。
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('請至少選擇一項!');
return false;
}
});
});
這段代碼會獲取所有 name='key' 的複選框,把選中項的 value 拼接後寫入隱藏域 <input type="hidden" name="ids" id="ids" value="" />,並在未選任何項時給出提示。
$("input[name='key']:checkbox").each(function () {
if (true == $(this).attr("checked")) {
ids += $(this).attr('value') + ',';
}
});
在 HTML 中,複選框被選中時標記為 checked="checked"。但如果用 jQuery 執行 alert($("#id").attr("checked")),返回的會是布爾值 true 而不是字符串 "checked"。因此,判斷 if ("checked" == $("#id").attr("checked")) 是錯誤的,正確的寫法應當是 if (true == $("#id").attr("checked"))。