Checkbox Select/Deselect Using JQuery

来源:互联网 发布:excel如何下拉选择数据 编辑:程序博客网 时间:2024/06/11 16:11

Almost all the user interfaces that I have created had this functionality of selecting multiple items from a list to process them or delete them. Although its very very easy to implement this functionality in Javascript, using jQuery for this is real fun. I will show you a simple implementation of adding multiple checkbox select and deselect functionality to any webpage. We will have a table with some data in it and checkbox in each row. There will be a select all checkbox in the header of the table. If user select/deselect the selectall checkbox, all the checkbox in table will get selected or deselected accordingly. Now one more thing we would like here to add is, suppose user select all the checkbox one by one then the selectall checkbox should be automatically gets selected. And if user click selectall first and then unchecks any of the checkbox, then the selectall also should be unchecked automatically.

The HTML

<HTML><HEAD><script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script><TITLE>Multiple Checkbox Select/Deselect - DEMO</TITLE></HEAD><BODY><H2>Multiple Checkbox Select/Deselect - DEMO</H2><table border="1"><tr><th><input type="checkbox" id="selectall"/></th><th>Cell phone</th><th>Rating</th></tr><tr><td align="center"><input type="checkbox" class="case" name="case" value="1"/></td><td>BlackBerry Bold 9650</td><td>2/5</td></tr><tr><td align="center"><input type="checkbox" class="case" name="case" value="2"/></td><td>Samsung Galaxy</td><td>3.5/5</td></tr><tr><td align="center"><input type="checkbox" class="case" name="case" value="3"/></td><td>Droid X</td><td>4.5/5</td></tr><tr><td align="center"><input type="checkbox" class="case" name="case" value="4"/></td><td>HTC Desire</td><td>3/5</td></tr><tr><td align="center"><input type="checkbox" class="case" name="case" value="5"/></td><td>Apple iPhone 4</td><td>5/5</td></tr></table></BODY></HTML>

The jQuery Code

Add following jQuery code in HEAD section of above HTML

<SCRIPT language="javascript">$(function(){// add multiple select / deselect functionality$("#selectall").click(function () {  $('.case').attr('checked', this.checked);});// if all checkbox are selected, check the selectall checkbox// and viceversa$(".case").click(function(){if($(".case").length == $(".case:checked").length) {$("#selectall").attr("checked", "checked");} else {$("#selectall").removeAttr("checked");}});});</SCRIPT>

Here in above code at line 05, we register a handler on click of selectall checkbox. On click of this checkbox, we check/uncheck all checkbox in the datatable.
Also check the link 13, where we check the selectall checkbox, if all the checkbox are selected manually. To get more idea, play with the below demo.

Online Demo

Click here to view Online Demo


http://viralpatel.net/blogs/multiple-checkbox-select-deselect-jquery-tutorial-example/

0 0
原创粉丝点击