แจก Code jQuery วิธีการจัดการกับ checkbox
// สร้าง function สำหรับกำหนดค่า checked ตามข้อมูลที่เคยใส่ไว้
//โดยดึงค่าจาก hidden field ใน format json เช่น [0,1,2,0,4,0]
function initCheck(chkId){
var json = $("#"+chkId).val();
json = jQuery.parseJSON(json);
$.each(json, function(index,val) {
$("#"+chkId+val).prop('checked', true);
});
}
//ทุกครั้งที่มีการ ติ๊ก checkbox ให้ทำการ ใส่ค่าให้ hidden field
function procCheck(chkId){
var txt="[0,"
$("."+chkId).each(function(i){
if($("#"+chkId+(i+1)).is(':checked')){
txt+=$("#"+chkId+(i+1)).val()+",";
}else{
txt+="0,";
}
});
txt+="0]";
$("#"+chkId).val(txt);
}
//ตัวอย่างการเรียกใช้งาน function
$(document).ready(function(){
initCheck("chk");
$(".chk").click(function(){
procCheck("chk");
});
});
ตัวอย่าง TAG HTML ขอเอา tag ออกนะครับเพราะ content ไม่ support
input type="hidden" id="chk" value="[0,1,2,0,4,0]"
input type="checkbox" id="chk1" value="1" class="chk"
input type="checkbox" id="chk2" value="2" class="chk"
input type="checkbox" id="chk3" value="3" class="chk"
input type="checkbox" id="chk4" value="4" class="chk"