Home > database >  I have two input elements with class "inputWithLimit". Why would both be firing simultaneo
I have two input elements with class "inputWithLimit". Why would both be firing simultaneo

Time:05-02

$(document).ready(function() {
    $(".inputWithLimit").each(() => {
        var inp = this;
        inp.addEventListener("input",
            function (event){
                console.log($(inp).val().length);
            });
    });
})

I've also tried "keyup" and "change" as event handlers, and in both other cases, jquery is doing a strange thing with assigning these listeners. Thanks.

CodePudding user response:

If you are using jQuery then there is no need to loop through each element and add an event listener. An example which logs the value of each input when you input something.

$(document).ready(function() {
    $(".inputWithLimit").on('input',function() {
        console.log(this.value);
    });
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input >
<input >

CodePudding user response:

The problem is your arrow function. When using arrow function, then you can't use `this'

$(".inputWithLimit").on("input", function() {
  console.log($(this).val().length);
});

I've also made your code shorter.

Demo

$(document).ready(function() {
  $(".inputWithLimit").on("input", function() {
    console.log($(this).val().length);
  });
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input  />

  • Related