Chriz74 Chriz74 - 4 months ago 10
jQuery Question

jQuery: attach event to 2 forms only in page with 3 forms

I have a page with 3 forms, every form has it's unique id. I also have two scripts, one should be invoked with two forms but not the third and another only with the third. I can attach the script to the third only by selecting it like this:

$("#third_form")


but how do I attach the other script to only the first and second form?
I tried to attach it to all forms like this:

$('form')


but obviously then this is attached to the
#third_form
too so I though I can check what form is submitted by

var form = $(this);

if (form != '#third_form'){ ... }


but it's not working.
Any idea?

Answer

You could use comma separator , to pass multiple selector :

$('#first_form,#second_form')

Hope this helps.

$('#first_form,#second_form').on('submit', function(){
  alert('First or Second_form');
})
$('#third_form').on('submit', function(){
  alert('Third form');
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id='first_form'>
  <input type='submit' value='First form submit'/>
</form>
<br/>
<form id='second_form'>
  <input type='submit' value='Second form submit'/>
</form>
<br/>
<form id='third_form'>
  <input type='submit' value='Third form submit'/>
</form>