-1

Here's my code in javascript:

function length(inputLength){
    this.inputLength = inputLength;
    document.getElementById('view').innerHTML = inputLength.length;
}

Normally, when I press a key, a counter is incremented and when I delete a char with the backspace key, the counter is decremented. The problem is when I delete a char, the count is incremented by 1 too then is decremented normally. Try this code by using the "onkeydown" event.

Can you help me?

mornaner
  • 2,424
  • 2
  • 27
  • 39
mathieu_b
  • 383
  • 1
  • 5
  • 19

1 Answers1

2

Why not simplify it and just do this :

​function calcLength(elem) {
    document.getElementById('output').innerHTML = elem.value.length;
}

Where elem is the input. Using elem.value.length will get the length of the content within the input.

An example of the HTML would be this

​<input id="testing" value="" onkeyup="calcLength(this)" />
Length = <span id="output"></span>​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​

Working example here

Manse
  • 37,765
  • 10
  • 83
  • 108
  • It's work, thanks! The solution is to use "onkeyup" instead "onkeydown". And thanks for the simplification! – mathieu_b Dec 11 '12 at 15:04
  • @MathieuBrochard im not sure the answer was the `onkeyup` vs `onkeydown` it really makes no difference - its just the order of execution ... read this http://stackoverflow.com/questions/3396754/onkeypress-vs-onkeyup-and-onkeydown – Manse Dec 11 '12 at 15:07
  • Apparently yes, I've replaced `onkeydown` by `onkeyup` and it's works... And don't worry, I wanted to validate your answer but I must wait 6 minutes :) – mathieu_b Dec 11 '12 at 15:07