Jquery遍歷checkbox獲取選中項value值的方法

Jquery遍歷checkbox獲取選中項value值代碼如下:

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"))

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *