How to find out what form I just submitted in jQuery?
I use the $.post
function to submit an ajax request as such:
$('.typeAform').submit(function(){
$.post('/home', { somevar : 'somevalue' }, function(){
//do something with the original form
});
return false;
});
I'd like to identify my form after submission from the $.post
callback so I can do something with it (i.e. change its background color, delete it, etc...).
Normally, I'd be able to call the form by its unique id that I know ahead of time, but here I don't have it - I am using a class for the form, not a single id.
Is there a way I can identify the form I just submitted withou开发者_如何转开发t using a global variable (i.e. pass it to the callback somehow).
Thanks!
EDIT:
Because the target of the submit
event should always be the form itself, you could also use the target
property of the event
object, as in: e.target
$('.typeAform').submit(function( e ){
$.post('http://apple.com', { somevar : 'somevalue' }, function(){
// e.target references the form that was submitted.
alert(e.target)
});
return false;
});
If this gives you trouble, then there are other ways to avoid creating a variable if you don't want that.
Get the ID from the DOM element in the .submit()
:
var id = this.id;
So it would be:
$('.typeAform').submit(function(){
var id = this.id;
$.post('/home', { somevar : 'somevalue' }, function(){
//do something with the original form
// Use the "id" here
});
return false;
});
Or if you want the form itself, just reference this
.
$('.typeAform').submit(function(){
var theForm = this;
$.post('/home', { somevar : 'somevalue' }, function(){
//do something with the original form
// Use the "theForm" here
alert( theForm.id );
$(theForm).someJQueryMethod()
});
return false;
});
Note that once you're inside the $.post
callback, this
no longer references the <form>
. That's why we referenced it in a variable.
精彩评论