Monday, September 6, 2010

Manipulating HTML checkbox using jQuery

A small simple example or tutorial on how to manipulate HTML checkboxes with javascript with the help of jQuery (v1.4.2).

Here, I've given a sample on how to
  • select (check) checkboxes
  • deselect (uncheck) checkboxes
  • reverse select (check/uncheck)
  • do something with your selected checkboxes

Hope anyone finds it useful as I have.

Here is the HTML of the selectors and the group of checkbox. A textbox is written below as I will use it to sample what you have selected.
<div>
  <a id="select_all">Select all</a> | <a id="deselect_all">Deselect all</a> |
  <a id="reverse_select">Reverse</a> | <a id="submit_select">Submit</a>
</div>
<ul id="checkbox_container">
  <li>
    <input id="checkbox_1" type="checkbox" value="1" />
    <label for="checkbox_1">Checkbox 1</label>
  </li>
  <li>
    <input id="checkbox_2" type="checkbox" value="2" />
    <label for="checkbox_2">Checkbox 2</label>
  </li>
  <li>
    <input id="checkbox_3" type="checkbox" value="3" />
    <label for="checkbox_3">Checkbox 3</label>
  </li>
  <li>
    <input id="checkbox_4" type="checkbox" value="4" />
    <label for="checkbox_4">Checkbox 4</label>
  </li>
</ul>
<input id="write_to_me" type="text" />

Here is the Javascript (jQuery) to use.
$(document).ready(function() {
  $("#select_all").click(function() {
    $("#checkbox_container").find(':checkbox').attr('checked', 'checked');
  });

  $("#deselect_all").click(function() {
    $("#checkbox_container").find(':checkbox').removeAttr('checked');
  });

  $("#reverse_select").click(function() {
    $("#checkbox_container").find(':checkbox').each(function() {
      if (this.checked)
        $(this).removeAttr('checked');
      else
        $(this).attr('checked', 'checked');
    });
  });

  $("#submit_select").click(function() {
    checks = new Array();
    $("#checkbox_container").find(':checked').each(function() { checks.push($(this).val()); });
    $("#write_to_me").val(checks.join(','));
  });
});

Good luck!

No comments:

Post a Comment