简体   繁体   中英

Jquery capturing multiple form events in one line?

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? ie something like

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

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() {

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.

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:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM