แรงจูงใจ …
เมื่อผู้ใช้ check เลือก item ที่ CheckBoxList บน form แล้ว ให้แสดงด้วยว่า เขาได้เลือกอะไรไปบ้าง
เตรียมตัวให้พร้อม …
1. เพิ่ม web form ใหม่ขึ้นมา ตั้งชื่อว่า DisplayCheckItems.aspx แล้วเติม control CheckBoxList ลงไป
<form id=”form1″ runat=”server”>
<div align=”left”>
<fieldset style=”width:400px;height:150px;”>
<p>รูปแบบของ packages ทั้งหมดที่สามารถเลือกได้:</p>
<asp:CheckBoxList ID=”CheckBoxList1″ runat=”server”>
<asp:ListItem Text=”มาตรฐาน” Value=”1″></asp:ListItem>
<asp:ListItem Text=”เงิน” Value=”2″></asp:ListItem>
<asp:ListItem Text=”ทอง” Value=”3″></asp:ListItem>
<asp:ListItem Text=”อย่างดี” Value=”4″></asp:ListItem>
</asp:CheckBoxList>
</fieldset>
<br />
<div id=”message”></div>
</div>
</form>
2. ลอง run form ขึ้นมา ตาม code ด้านบนจะแสดงคล้ายๆรูปข้างล่างนี้
วิธีทำ …
1. ในฟังชั่น document.ready() กำหนดฟังชั่น click ให้ CheckBoxList
$(‘#<%=CheckBoxList1.ClientID%>’).click(function() {
2. สร้างตัวแปรไว้เก็บข้อมูลจาก item ที่ถูก check
var str = “”;
3. ประยุกต์ใช้ jQuery ค้นหาทุกๆ check box แล้วใช้ฟังชั่น each เพื่อเพิ่มฟังชั่นเข้าไปในทุกๆ check box item
$(‘#<%=CheckBoxList1.ClientID%> input[type=checkbox]:checked’).each(function() {
4. ภายในฟังชั่นจาก 3 ที่ถูก jQuery ค้นมาได้นั้นให้เอาข้อความจาก item ซึ่งเราจะอ้างถึงโดยใช้ this มาเพิ่มในตัวแปร str ที่ทำไว้จาก 2
str = str + ” ” + $(this).next().text();
5. ใช้ jQuery ค้น id message ขึ้นมาแสดง str
$(‘#message’).text(str);
});
jQuery ที่เสร็จแล้วจะออกมาหน้าตาแบบนี้
<script type=”text/javascript”>
$(document).ready(function() {
$(‘#<%=CheckBoxList1.ClientID%>’).click(
function() {
var str = “”;
$(‘#<%=CheckBoxList1.ClientID%> input[type=checkbox]:checked’).each(function() {
str = str + ” ” + $(this).next().text();
});
$(‘#message’).text(str);
});
});
</script>
ทดสอบการทำงาน…
พอ run form DisplayCheckItems นี้ขึ้นแล้วลองติ๊กตรงกล่องของ check box สักสองสามอัน ก็จะได้หน้าตาออกมาคล้ายแบบนี้
… ขอให้สนุกกับการเขียนรหัส …
ขอบคุณครับ