Reputation: 7543
I have this simple form & validation and everything works perfectly fine excepting 'this' points to, well, I have no idea what:
$('#contact').validator().submit(function(e){
e.preventDefault();
$.ajax({
type: "POST",
url: this.action,
data: {
mail: jQuery('input[name="mail"]').val(),
message: jQuery('textarea[name="message"]').val(),
success: function(){
$(this).hide();
}
});
});
I want this code to hide #contact on success but this never happens.
I tried to alert(this)
, but I'm getting [object Object]
, the same happened when I did console.log( $(this) )
(there's only Object with + next to it and when I click + I see all sorts of data excepting class / id of this element :( ). Any ideas? Is there something wrong with my code?
Upvotes: 0
Views: 106
Reputation: 30453
You lose the context. In submit
function #contact
element is the context. In ajax callback ajax settings is the context.
From jQuery Documentation:
The this reference within all callbacks is the object in the context option passed to $.ajax in the settings; if context is not specified, this is a reference to the Ajax settings themselves.
$('#contact').validator().submit(function (e) {
e.preventDefault();
var self = this;
$.ajax({
type: "POST",
url: this.action,
data: {
mail: jQuery('input[name="mail"]').val(),
message: jQuery('textarea[name="message"]').val(),
success: function () {
$(self).hide();
}
});
});
});
Upvotes: 1
Reputation: 144689
this
within the context of success
method doesn't refer to the clicked element, you should cache the element:
$('#contact').validator().submit(function(e){
e.preventDefault();
var $this = $(this); // cache the object
$.ajax({
type: "POST",
url: this.action,
data: {
mail: jQuery('input[name="mail"]').val(),
message: jQuery('textarea[name="message"]').val()
}, // missing }
success: function(){
$this.hide();
}
});
});
Upvotes: 1