Length of content returning incorrect value

2

I have this code to check if the size of the user input conforms to some parameters, but the size it returns is always -1 the size of the input content, would it 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><inputtype="number">
    
asked by anonymous 19.04.2017 / 14:42

1 answer

5

For this check use the .keyup event instead of .keydown , since the new character will only actually be included after the .keyup event. Here is a working 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><inputtype="number">
    
19.04.2017 / 14:47