Razib Razib - 1 month ago 6
jQuery Question

Getting the actual id from where slector works on multiple id

I'm working with

jqury
. I have a
javascript
method which works on two selector like this -

$('#from1, #form2').submit(function() {
....
....

//is there any way to know the actual id (that is - form1 or form2)
//for which the submit() method is called
}


This is a pretty large method and two of the form (
form1
and
from2
) share almost the same code so that I don't want to write multiple
submit()
method for each form separately. So is there any way to get the actual
id
for which the
submit
method is called.

Answer
$(this).attr('id')

$(this) will point to the form that triggered the submit event.

This is the common syntax in all the event handlers. this will point to the element that triggers an event and $(this) will make it a JQuery object so that you can use many built in JQuery syntax on it, just like how we have used .attr('id')

Comments