Ad

Wednesday 11 June 2014

To check/uncheck the Checkboxes using Jquery


We may need to precheck a check box, when the page loads or we may need to check it depending on any event.Using Jquery it is very simple and easy to implement.Below is the sample code to check or uncheck a single check box or all checkboxes.

<html>                                                                                                                                                    
<head>
<title>CheckBox sample</title>
<script type="text/javascript" src="jquery-2.1.1.min.js" ></script>
<script type="text/javascript">

function check() {
   $("#checkbox1").prop("checked", true);
}

function uncheck() {
   $("#checkbox1").prop("checked", false);
}

function checkall() {
   $("#checkGrp input[type=checkbox]").each(function()
    {
      $(this).prop("checked",true);
    } );
}

function uncheckall() {
   $("#checkGrp input[type=checkbox]").each(function()
   {
    $(this).prop("checked",false);
   });
}
</script>
</head>
<body bgcolor=white>

<input type="checkbox" id="checkbox1"/>BreakFast
<BR>
<input type="button" value="check" onclick="check()"/>
<input type="button" value="uncheck" onclick="uncheck()"/>
<BR><BR>
<div id="checkGrp">
<input type="checkbox" id="checkbox2"/>Coffee
<BR>
<input type="checkbox" id="checkbox3"/>Tea
<BR>
<input type="checkbox" id="checkbox4"/>Bread
<BR>
<input type="checkbox" id="checkbox5"/>Burger
<BR>
<input type="button" value="CheckAll" onclick="checkall()"/>
<input type="button" value="UncheckAll" onclick="uncheckall()"/>
</div>
</body>
</html>

  • To check the Checkbox,we set the Property of the checkbox with id "checkbox1" to true as shown in function check()
  • To uncheck the Checkbox,we set the Property of the checkbox with id "checkbox2" to false as shown in function uncheck()
  • To checkall the checkboxes,we iterate all the checkboxes object under the div "checkGrp" and set the property of each checkbox to true as shown in function checkall().
  • To uncheck all the checkboxes,we iterate all the checkboxes object under the div "checkGrp" and set the property of each checkbox to false as shown in function uncheckall().

Demo

BreakFast


Coffee
Tea
Bread
Burger

No comments:

Post a Comment