1

I have an input with maxLength of 1. I want that if I type another value (key) the current value (letter) that inside the input will be replaced with the new value (letter of key).

I've tried something like that:

container.addEventListener('keyup', function (e) {
    var target = e.srcElement || e.target;
    var letter = target.value;
    var newLetter = letter.replace(/letter/g, letter);
    letter.value = newLetter;
});
2
  • 1
    but if you limit the maxlength to 1 how will you be able to type another letter? Commented Dec 9, 2019 at 11:51
  • @RamRaider as I said, I don't want another letter, I want the letter to be replace on each time I type in new value.. Commented Dec 9, 2019 at 11:54

2 Answers 2

5

You can update the value of the input box using this.value and get the key pressed using e.key. This will, however, enter meta keys if pressed:

const container = document.getElementById('container');
container.addEventListener('keyup', function(e) {
  this.value = e.key;
});
<input type="text" id="container" maxlength="1" />

The issue with the meta keys could be fixed by checking whether or not e.key is an alphabetic/digit letter by using a regular expression:

const container = document.getElementById('container');
container.addEventListener('keyup', function({key}) {
  if(/^[a-z0-9]$/i.test(key)) {
    this.value = key;
  }
});
<input type="text" id="container" maxlength="1" />

Sign up to request clarification or add additional context in comments.

8 Comments

please add some form of a validation in case of special keys, for instance if i were to press Enter the input field value will be a string "Enter" which is probably not what the author intended
@KrzysztofKrzeszewski Hi, thanks for the tip. I've added some validation (in the second code snippet)
@KooiInc oh, you're right, what would be a better alternative to get the key code? (.code will give a string)
@NickParsons The {key}-check is fine, the RegExp can be simplified to /^[a-z0-9]$/i. Up for discussion is if you want to use this or event.target
|
1

This works for all single character inputs while excluding the space character:

let container = document.getElementById('container');

container.addEventListener('keyup', function (e) {
  let valueLength = this.value.length;

  if(this.value == " ") {
      this.value = "";
      return;
  }
  
  if(valueLength == 1) {
    if( !e.altKey && !e.ctrlKey && !e.shiftKey && !e.metaKey 
        && e.code != "Space" && e.key.length == 1) {
      this.value = e.key;
    }
  }
});
<input id="container" type="text" value="" maxLength="1" />

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.