I have lots of text inputs and want to toggle the input field background green for 2 seconds to indicate success of a future ajax firing etc., but only for the field that changed. Not wrapping my head around this with jQuery.
So below… if I change the value of stats.1a to 5 only toggle stats.1a field to green and back… not all the others stats fields also. Etc.
Or am I just going about this the wrong way?
jQuery(document).ready(function($) {
$('[name="stats"]').on('change', function() {
$('[name="stats"]'.id).css("background-color", "#adf0c2");
setTimeout(function() {
$('[name="stats"]'.id).css("background-color", "#ffffff");
}, 2000);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" name="stats" id="1a" value="">
<input type="text" name="stats" id="2a" value="">
<input type="text" name="stats" id="3a" value="">
2
Answers
You can refer to the element which raised the event by using
this
within thechange
handler. It’s the element itself, not a jQuery object, but any element can be wrapped in a jQuery object:From there, all you’d need to do is capture that reference in a variable so the
setTimeout
callback can close around that variable and still use the same reference 2 seconds later.For example:
Try this:
The main problem in your code is the following line:
To add CSS properties to an element, write
$(element).css("key", "value")
instead.By the way, the
name
attribute is used for HTTP requests (POST, GET) to the server, it may be more appropriate to use classes. If you need to identify the inputs, writestats[]
, otherwise each one will be overwritten by the next input with the same value until the last one is reached.So something like this would make more sense: