Select grouped checkboxes in jQuery


Have you ever noticed in gmail where we  select/deselect all the visible mails with the help of a checkbox given on top? Now it is possible to do it in a single line of javascript. For that purpose, you need to use jQuery.

Suppose you have a bunch of checkboxes having same id as show below:

Parent Checkbox:

<input type="checkbox" id='parent_id' />

Grouped Checkboxes:

<input type="checkbox" id='result_data_id' name="result_data_1" value="1" />
<input type="checkbox" id='result_data_id' name="result_data_2" value="2" />
<input type="checkbox" id='result_data_id' name="result_data_3" value="3" />
<input type="checkbox" id='result_data_id' name="result_data_4" value="4" />
<input type="checkbox" id='result_data_id' name="result_data_5" value="5" />

Now we have to attach onchange event to our parent checkbox this way:

$('#parent_id').change(function () {
$('input[id=result_data_id]').attr('checked', this.checked);
});

That’s it. Isn’t that simple and fun? BTW, do not forget to drop a comment.

Advertisements

One thought on “Select grouped checkboxes in jQuery

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s