How to react on input text events in jquery?

I’m trying to react on <input> events with jquery, to modify a background label in as soon as the input contains text:

$('#inpt').on('input', ':text', function() {
  Window.alert("test");
  $('#mytext').attr('background', 'red');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
  <input id="inpt" type="text" placeholder="Type in here" />
</div>

<span id="mytext" style="background:green">Test</span>

Result: nothing happens. I don’t even get the alert. Why?

4 thoughts on “How to react on input text events in jquery?”

  1. Using Pure JS and Not JQuery Library.

    document.getElementById("inpt").addEventListener('input', (eve)=>{
      document.getElementById("mytext").innerHTML = eve.target.value;
    })
    
    Reply
  2. You should use with document and keyup

    $(document).on('keyup', '#inpt', function() {
       alert("test");
      $('#mytext').css({'background': 'red'});
    });
    
    Reply
  3. The problem here that you use selector inside you on function cause the $(‘#inpt’) is the container for looking the selector. But in this case the container is the selector (:input) you define in on() function too then it doesn’t work and the Window wrong typo too.

    attr is use to update the attribute of the element and background is not included inside attr list. Then you should wrap the background: red inside style attr or using css({background:red})

    $('#inpt').on('input', function() {
        window.alert("test");
      $('#mytext').attr('style', 'background:red');
    });
    
    Reply

Leave a Comment