DR01D
DR01D

Reputation: 1365

Why does text input continue for 1 character past its max length restriction?

In an input box I used e.preventDefault(); to stop text input after inputValue.length > 10. However text input always stops at 11 characters instead of 10. I can't understand why it doesn't stop accepting characters at 10. Why is this? Thanks so much!

'use strict';
	
document.querySelectorAll('.input_style')[0].addEventListener('keydown', pressKey);	
document.querySelectorAll('.input_style')[0].addEventListener('keyup', releaseKey);

function pressKey(e) {
  let inputValue = e.target.value;		
  if (inputValue.length > 10) {
    e.preventDefault();
  }
}

function releaseKey(e) {
  let inputValue = e.target.value;
  console.log(inputValue.length);
  if (inputValue.length > 10 ) {
    e.preventDefault();
  }
}
.input_style {
  font-size: 2rem;
  font-family: arial;
}
<input class="input_style">

Upvotes: 0

Views: 42

Answers (3)

Claies
Claies

Reputation: 22323

The issue here is that new values are added to the input on keydown, not keyup, and your keydown handler pressKey(e) is checking for the current value of the input box, before adding the new value. Therefore, you need to check for your length >= 10 rather than >10.

The keyup handler in this case is completely unnecessary, since it does not stop a new value from being added.

Another thing you should consider is checking for the input keycode values 8 ("backspace") and 46 ("delete"), and allow those to be handled. As it stands now, once your input box is full, it is impossible to change it in any way, as you can't use backspace or delete to remove a wrong character.

Upvotes: 1

Juan Cort&#233;s
Juan Cort&#233;s

Reputation: 21112

Your condition waits until it's bigger than 10, so that condition is only met when it's 11.

Upvotes: 1

Barbara Laird
Barbara Laird

Reputation: 12717

The length of the string has to be 11 for the condition > 10 to be true. If you want to stop at 10, do >= 10.

Upvotes: 3

Related Questions