1

I have function with onkeydown() event and get value length of input text, when I press ctrl+a / block a text (with 5 character) on it and type single character but **ouput value length of input is 4 instead 0.

function typeInput(that) {
  console.log($(that).val().length);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" onkeydown="typeInput(this)">
Alive to die - Anant
  • 70,531
  • 10
  • 51
  • 98
itx
  • 1,327
  • 1
  • 15
  • 38

2 Answers2

3

Just a couple things. I really like the this keyword so I normally bind my events, like as follows. Additionally, I think you want the onkeyup instead of onkeydown, because onkeydown is fired before the newest character is added to the .val().

function typeInput(){
   console.log($(this).val().length);
} 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" onkeyup="typeInput.bind(this)()">
Neil
  • 14,063
  • 3
  • 30
  • 51
  • This is the actual answer, the issue with the original question was the fact after he _cleared_ the input it was still outputting the length of the old text. – George Apr 12 '17 at 08:03
  • Exactly, why I still using `onkeydown` instead of `onkeyup`? I want prevent enter key on input, I have follow on this question [disable form submit on enter](http://stackoverflow.com/questions/11235622/jquery-disable-form-submit-on-enter), if I using `onkeyup` and press `enter` key, submit form still firing. I know that is different problem with my question now but it's still have relation. thanks @nfn neil – itx Apr 12 '17 at 08:12
  • Oh, you need to target the form when preventing submit. – Neil Apr 12 '17 at 08:22
  • @nfnneil you are very fast.+1 – Alive to die - Anant Apr 12 '17 at 09:08
  • @AlivetoDie Thanks. – Neil Apr 12 '17 at 09:09
2
<input type="text" onkeydown="typeInput.bind(this)()">

Rest code is completely fine.

Working example:-

function typeInput(that) {
  console.log($(this).val().length);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" onkeyup="typeInput.bind(this)()">
Alive to die - Anant
  • 70,531
  • 10
  • 51
  • 98