Length of content returning incorrect value

Asked

Viewed 37 times

2

I have this code to check if the size of the user input is in accordance with some parameters, but the size it returns is always -1 the size of the input content, it would be the case to convert to int and add 1?

$("input").keydown(function() {
  console.log($(this).val().length);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="number">

  • 1

    Tried keyup instead of keydown?

  • That’s exactly what Maurivan.

1 answer

5


W/ this check use the event .keyup instead of .keydown, since the new character will only be included in fact after the event .keyup. Follow a functional example returning the correct value:

$("input").keyup(function() {
  console.log($(this).val().length);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="number">

  • Ahh now I understand thank you very much

Browser other questions tagged

You are not signed in. Login or sign up in order to post.