Apply the input class active if the field is not empty



  • Here's HTML.

    <input type="number" placeholder="" />
    

    JS

    $("input").on("keyup", function(e) {
        if($(this).val() != "") {
            $(this).addClass("active");
        }
    });
    

    Only figures can be inserted in input[type='number']. But the "e" symbol is being introduced. We need to check if the field isn't empty, then assign him the active class. If the "e" symbol is accidentally introduced, the active class needs to be assigned. We need a class to be assigned if the field is not empty. How do you do that?



  • I think it's better to put the processor on the event. inputNot on keyup:

    $('input').on('input', function() {
      $(this).toggleClass('active', ($(this).val() != '' && !/e/gi.test($(this).val())));
    });
    .active { background-color: cyan; }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    

    <input type="number" placeholder="" />



Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2