Change input style with AJAX

I have the following AJAX code that works correctly, except for the part where I want to add the class to the input field that it just checked.

Entry field:

<input type="text" class="solution" id="input_rebus" name="answer" /> 

AJAX Code:

  $('.solution').on("change", function(){ var form_data = { name: $(this).val(), ajax: '1' }; $.ajax({ url: "<?php echo site_url('homework/submit'); ?>", type:'POST', data: form_data, success: function(msg){ $('#message').html(msg); this.addClass('solution_correct'); //outputs: Correct! }, error: function(msg){ $('#message').html(msg); this.addClass('solution_wrong'); //outputs: Wrong! Try again! } }); return false; }); </script> 

So, the problem would be in the line "this.addClass (" ... "); I tried to use $ (this), but that didn't work either.

This is probably something really stupid, but I can't figure it out!

Thanks in advance:)

+1
source share
2 answers

You can set the context property when calling $ .ajax, which will be set to this in all callbacks.

  $('.solution').on("change", function(){ var form_data = { name: $(this).val(), ajax: '1' }; $.ajax({ url: "<?php echo site_url('homework/submit'); ?>", type:'POST', context: $(this),//<--- here data: form_data, success: function(msg){ $('#message').html(msg); this.addClass('solution_correct'); //outputs: Correct! }, error: function(msg){ $('#message').html(msg); this.addClass('solution_wrong'); //outputs: Wrong! Try again! } }); return false; }); </script> 
0
source

this is the way to do it

  $('.solution').on("change", function(){ var $self = $(this); var form_data = { name: $(this).val(), ajax: '1' }; $.ajax({ url: "<?php echo site_url('homework/submit'); ?>", type:'POST', data: form_data, success: function(msg){ $('#message').html(msg); $self.addClass('solution_correct'); //outputs: Correct! }, error: function(msg){ $('#message').html(msg); $self.addClass('solution_wrong'); //outputs: Wrong! Try again! } }); return false; }); 
0
source

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


All Articles