How to update style after ajax call in jQuery?

I have dynamically adding input fields like this:

<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 the add 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 he did not add the class 'make_it_red' to my input field (I also tried html ('foo') and other things, and it also doesn't work). I think this is because I run $ (this) inside another function, but I don't know what to do with it. $ (this) .val () works, and I also get the correct answer (alert (data)). Can anyone help?

+4
source share
2 answers

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

 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"); }); } 
+6
source

You can refer to an element by id:

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

In addition, it depends on how you dynamically inserted the element, if you just added it as a string to some div, for example, it cannot be bound to the DOM.

EDIT: you can get the identifier of the element from the binding and build a selector in 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"); }); } 
+2
source

Source: https://habr.com/ru/post/1286233/


All Articles