วันพุธที่ 24 กันยายน พ.ศ. 2557

jQuery กับการเลือก CheckBox ทั้งหมด


    วันนี้จะขอแนะนำโค๊ดของ jQuery ที่เกี่ยวข้องกับการเลือก CheckBox ทั้งหมด (Select All) โดยโค๊ดที่ผมนำเสนอนี้ จะมี 2 ส่วน คือ สำหรับ jQuery เวอร์ชั่นต่ำกว่า 1.6 กับเวอร์ชั่น 1.6 หรือสูงกว่า
    เพราะ jQuery ตั้งแต่ 1.6 ขึ้นไปจะมีฟังก์ชั่นที่ว่า prop เข้ามาเพื่อตรวจสอบการกระทำกับเหตุการณ์ ที่เกิดขึ้น 2 เหตุการณ์ เช่นการติ๊กเลือกที่ CheckBox หรือ ไม่ติ๊กเลือก CheckBox ทำให้การเขียนคำสั่งกับ jQuery 1.6 หรือเวอร์ชั่นที่สูงกว่า ไม่ซับซ้อน และได้ผลลัพธุ์ที่รวดเร็วยิ่งขึ้นครับ

มาดูโค๊ดกันเลยครับ
1. สำหรับ jQuery เวอร์ชั่นต่ำกว่า 1.6 ซึ่งไม่มีฟังก์ชั่น prop เราจะใช้คำสั่งเหล่านี้แทนครับ

$(function() {
     $('#selectAll').change(function () {
  //ใช้ได้กับ jQuery เวอร์ชั่นต่ำกว่า 1.6
  if($(this).attr('checked')){//ตรวจสอบว่า checkbox  id=selectAll ถูกเช็คอยู่หรือไม่ ถ้าถูกเช็คอยู่
  $('.product_select').each(function() {//วนลูป checkbox class=product_select  ทั้งหมด
   $(this).attr('checked','checked'); //กำหนด class=product_select ให้ถูกเช็ค(checked)ทั้งหมด
   //โดยเพิ่ม attribute คือ checked="checked" เข้าไปทั้งหมด
  });
  }else{//ถ้าไม่ถูกเช็ค หรือติ๊กออก
   $('.product_select').each(function() {//วนลูป checkbox class=product_select ทั้งหมด
   $(this).removeAttr('checked');//ลบ attribute checked="checked" ออกจาก checkbox class=product_select ทั้งหมด
  });
  }
       });
});

2. สำหรับ jQuery เวอร์ชั่น 1.6 หรือสูงกว่า โดยใช้ฟังก์ชั่น prop เราจะใช้คำสั่งสั้นๆดังนี้

$(function() {
     $('#selectAll').change(function () {//เมื่อมีการติ๊กที่ checkbox id=selectAll
 //สำหรับ jQuery เวอร์ขั่น 1.6 หรือสูงกว่า
        $('.product_select').prop('checked', function(){
               return $('#selectAll').is(":checked"); 
       });
    }); 
});

สำหรับไฟล์ html ตัวอย่าง ให้ใช้codeดังนี้ครับ

<table width="500" border="1" align="center">
<tr>
<td><strong>รหัสสินค้า</strong></td>
<td><strong>ชื่อสินค้า</strong></td>
<td><strong>เลือก
<input type="checkbox" name="selectAll" id="selectAll">
</strong></td>
</tr>
<tr>
<td>iPhone6-16</td>
<td>iPhone 6 16GB</td>
<td><input type="checkbox" name="product_select[]" class="product_select">
</td>
</tr>
<tr>
<td>SS-Note4</td>
<td>Samsung Galaxy Note 4</td>
<td><input type="checkbox" name="product_select[]" class="product_select">
</td>
</tr>
<tr>
<td>HTC-M8</td>
<td>HTC ONE M8</td>
<td><input type="checkbox" name="product_select[]" class="product_select"></td>
</tr>
</table&gt

ไม่มีความคิดเห็น :

แสดงความคิดเห็น