In the code example below the success callback function logs 'input#04.update' four times rather than each individual input, which makes sense seeing how closures work but how would I go about targeting each individual input using this.
<input type="text" name="" id="01" class="update">
<input type="text" name="" id="02" class="update">
<input type="text" name="" id="03" class="update">
<input type="text" name="" id="04" class="update">
function updateFields(){
$('input.update').each(function(){
$this = $(this);
$.ajax({
data: 'id=' + this.id,
success: function(resp){
console.log($this);
$this.val(resp)
}
});
});
}
In the code example below the success callback function logs 'input#04.update' four times rather than each individual input, which makes sense seeing how closures work but how would I go about targeting each individual input using this.
<input type="text" name="" id="01" class="update">
<input type="text" name="" id="02" class="update">
<input type="text" name="" id="03" class="update">
<input type="text" name="" id="04" class="update">
function updateFields(){
$('input.update').each(function(){
$this = $(this);
$.ajax({
data: 'id=' + this.id,
success: function(resp){
console.log($this);
$this.val(resp)
}
});
});
}
Share
Improve this question
asked Jun 11, 2010 at 13:45
screenm0nkeyscreenm0nkey
18.9k18 gold badges62 silver badges75 bronze badges
2 Answers
Reset to default 12You forgot var
var $this = $(this);
Don't forget var
. One programmer who forgot var
went to bed at night and woke up to find his apartment on fire. He added var
and the fire went out. Another programmer left var
out pletely shortly before leaving on a business trip to Europe. The airplane developed in-flight mechanical problems shortly after takeoff, causing the pilot to initiate emergency landing procedures. From his laptop the programmer quickly added var
and the plane made it safely to an airport.
Don't forget var
. If you put var
in your code, you'll meet somebody special today. Try it. It sounds amazing but it really works!
Pointy's correct on var
usage, another alternative is to use $.proxy()
, like this:
function updateFields(){
$('input.update').each(function(){
$.ajax({
data: 'id=' + this.id,
success: $.proxy(function(resp){
$(this).val(resp);
}, this)
});
});
}
This closure creator will make this
refer to the input element when you're inside the success
callback, which is usually what you're after...so I'm not sure why this isn't the case by default, but in any case $.proxy()
rectifies the situation.