views:

15

answers:

3

I have the following to capture the checkbox check event of form with id="form1":

$('#form1 :checkbox').click(function() {
  var $this = $(this);
  alert($this.val());
}

I now have another form (id="form2") with checkboxes for which I need to handle events. Is there any way to combine both forms into a single line and have the alert still pop up the correct value? i.e. something like

$('#form1 OR #form2 :checkbox').click(function() {
  var $this = $(this);
  alert($this.val());
}
A: 

You ca do it using a multiple-selector like this:

$('#form1 :checkbox, #form2 :checkbox').click(function() {

Or .find(), to make it a bit shorter, like this:

$('#form1, #form2').find(':checkbox').click(function() {
Nick Craver
looks like you answered first (by a few seconds) so I'll accept your answer. thanks
aeq
A: 

Try this:

$('#form1, #form2').find('input:checkbox').click(function() { ... });


edit: this is a side note, but use 'input:checkbox' instead of ':checkbox'. This allows the selector engine to only filter input tags that are checkboxes, rather than all tags that are checkboxes, and is therefore a lot faster.

jmar777
A: 

Is there any way to combine both forms into a single line and have the alert still pop up the correct value?

Yes:

Using a comma

$('#form1 :checkbox, #form2 :checkbox').click(function() {
  var $this = $(this);
  alert($this.val());
};

Or Using add method

$('#form1 :checkbox').add('#form2 :checkbox').click(function() {
  var $this = $(this);
  alert($this.val());
};

More Info:

Sarfraz