skip to Main Content

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


  1. You can refer to the element which raised the event by using this within the change handler. It’s the element itself, not a jQuery object, but any element can be wrapped in a jQuery object:

    $(this)
    

    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:

    $('[name="stats"]').on('change', function(){
      const $self = $(this);
      $self.css("background-color", "#adf0c2");
          setTimeout(function(){
              $self.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="">
    Login or Signup to reply.
  2. Try this:

    jQuery(document).ready(function($) {
      $("input").on("change", function() {
        $(this).css("background-color", "#adf0c2");
        setTimeout(() => {
          $(this).css("background-color", "#ffffff");
        }, 2000);
      });
    });
    

    The main problem in your code is the following line:

    $('[name="stats"]'.id).css("background-color", "#adf0c2");
    

    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, write stats[], 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:

    <input type="text" name="stats[]" class="stats">
    <input type="text" name="stats[]" class="stats">
    <input type="text" name="stats[]" class="stats">
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search