views:

348

answers:

2

I have dynamicaly added input fields like this one:

<input id="person__1_badge_number" class="number" type="text" size="12" name="person[][1][badge][number]"/>

And when I add this field I call fallowing function:

function please_rebind() {
  $('.number').bind("change", function() {
    $.post('/registration/sell/check_badge_number', { number: $(this).val() },
    function(data) {
      $(this).addClass('make_it_red');
      alert(data);
    }, "html");
 });
}

And it didn't add 'make_it_red' class to my input field (I also tried html('foo') and other stuff and it also doesn't work). I think it is becouse I run $(this) inside other function, but I don't know what to do with it. $(this).val() works and I also get correct response (alert(data)). Can anybody help?

+2  A: 

You can reference the element by id:

$('#person__1_badge_number').addClass('make_it_red');

Also, it depends on how you've dynamically inserted the element, if you just appended it as a string to some div, for example, it may not be bound to the DOM.

EDIT: you can get the element ID from within the binding, and build the selector within the callback:

 function please_rebind() {
  $('.number').bind("change", function() {
    var elementId = this.id;
    $.post('/registration/sell/check_badge_number', { number: $(this).val() },
    function(data) {
      $('#' + elementId).addClass('make_it_red');
      alert(data);
    }, "html");
 });
}
karim79
But I add these fileds dynamicaly and id is different in every field. This is why I select it by class $('.number'), so this could be solution if I'd knew id, but I don't. If you know how to do it, I'll be glad :)
klew
@klew - see my edit
karim79
Thanks, it works, but Jose answer is clearer.
klew
+4  A: 

I think what is happening is that after the callback, the reference to $(this) is lost. Try it this way:

function please_rebind() {
  $('.number').bind("change", function() {
    var that = $(this);
    $.post('/registration/sell/check_badge_number', { number: $(this).val() },
    function(data) {
      that.addClass('make_it_red');          
    }, "html");
 });
}
Jose Basilio
Just wanted to add that "this" within the callback for $.post refers to the options for the given ajax request.
ayaz
Thanks, it work!
klew
this is one of the recurring thorns in JS, the volatility of 'this'. just remember to use this trick whenever you define a callback. Of course, this makes the function a full closure, which is considered 'bad practice' performance-wise by IE developers. they prefer to keep JScript non-performant on these cases.
Javier