Delphinidin

Get any informations you need in depth explanation

You can use jQuery to programmatically select and deselect all of the check boxes on a Web page, a technique that is often used with a preferences section on a Web site. The user sees 20 or so check boxes and a link that lets them select all of the check boxes with a single click. The following tutorial shows you how you can set up a Check All Check Boxes link using the jQuery click event and conditional logic.

1. First, set up five check box input elements in an unordered list with an ID of form-fields and apply the class check to each check box element.

<ul id="form-fields">
<li><input name="check1" class="check" type="checkbox"/> <label>Checkbox 1</label></li>
<li><input name="check2" class="check" type="checkbox"/> <label>Checkbox 2</label></li>
<li><input name="check2" class="check" type="checkbox"/> <label>Checkbox 3</label></li>
<li><input name="check2" class="check" type="checkbox"/> <label>Checkbox 4</label></li>
<li><input name="check2" class="check" type="checkbox"/> <label>Checkbox 5</label></li>
</ul>

2. Add an input check box with an ID of checkall directly before the list of check boxes. This check box is used to control the checking and un-checking of the inputs.

<input type="checkbox" id="checkall" /> <label>Check all</label>

3. Select the #checkall element and attach a click event.

$('#checkall').bind('click', function(){
});

4. Add a variable called checkboxes and a statement that selects all the list items found in the unordered list and searches for all of those with the class check. The variable will hold this matched set:

$('#checkall').bind('click', function(){
var checkboxes = $('#form-fields li').find('.check');
});

5. You can optionally add if and else statements to test if the input #checkall element is checked or un-checked, if you want to give the option to check and uncheck all check boxes. If the element is checked, apply the attribute 'checked','true' to all of the check boxes contained in the matched set of the checkboxes variable that you set up in the previous step. If the element is not checked, remove the checks from all of the check boxes contained within the variable checkboxes.

$('#checkall').bind('click', function(){
var checkboxes = $('#form-fields li').find('.check');
if (this.checked) {
checkboxes.attr('checked', 'true');
}
else {
checkboxes.attr('checked', 'false');
};
});

When you test the final code in the browser, you should see a smooth, flexible check/uncheckfunction for managing multiple check boxes.

0 comments:

Post a Comment

Site Info