Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to update style after ajax call in jQuery?

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?

like image 973
klew Avatar asked Feb 28 '23 15:02

klew


1 Answers

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");
 });
}
like image 158
Jose Basilio Avatar answered Mar 11 '23 22:03

Jose Basilio