Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

193
Visualizações
How to type unique letters only in input text box in html or react?

I want to create an input box that allows to type only a distinct alphabet letter in the input box ( No duplicate alphabet value, ONLY ONE)

I looked up all the attributes for input box but I couldn't find one and there were no example.

Do I have to handle it within JavaScript functions? (I am using React)

<input
            className="App-Contain-Input"
            name="containedLetter"
            type={"text"}
            onChange={containedChange}
          />
about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

Here is how this can be done, note that we have to use onkeydown which fires when a key is being pressed, but not before it is being released (this way we can intercept and prevent the key stroke from being taken into account):

function MyInput() {

  const containedChange = (event) => {
    if (event.key.length === 1 && event.code.startsWith('Key') && event.code.length === 4 && event.target.value.indexOf(event.key) !== -1) {
      event.preventDefault()
      return false;
    }
    
    return true
  }
          
          
  return (
    <input
      id="input"
      className="App-Contain-Input"
      name="containedLetter"
      type="text"
      onkeydown={containedChange}
    />
}
about 4 years ago · Juan Pablo Isaza Relatório

0

A way to do it with a cheeky two-liner is to get rid of any non-letters with regex, then let Set do the de-duping by converting to Array => Set => Array => String:

As a side note, many of the other solutions posted here make one or both of two assumptions:

  1. The user is only ever going to edit the last character... but what if they edit from the beginning or middle? Any last character solution will then fail.
  2. The user will never copy/paste a complete value... again, if they do, most of these solutions will fail.

In general, it's best to be completely agnostic as to how the value is going to arrive to the input, and simply deal with the value after it has arrived.

import { useState } from 'react';

export default function Home() {
    const [value, setValue] = useState('');

    return (
        <div>
            <input
                type='text'
                value={value}
                onChange={(e) => {
                    const onlyLetters = e.target.value.replace(/[^a-zA-Z]/g, '');
                    setValue(Array.from(new Set(onlyLetters.split(''))).join(''));
                }}
            />
        </div>
    );
}
about 4 years ago · Juan Pablo Isaza Relatório

0

One pure js solution would be to handle the input value in onkeyup event where we have access to the latest key as well as updated input target value.

If the latest key pressed is duplicate then we will found it on 2 location in the target value, first on some where middle of the target value and second at the end of the target value. So we can remove the value at the end (which is the duplicate one).

The below code snippet shows the implementation of above in React

const Input = () => {
  const handleKeyUp = (e) => {
    const { key, target: { value }} = e;
    const len = value.length;

    if (value.indexOf(key) < len - 2) {
        e.target.value = value.slice(0, len - 1);
    }
  }

  return (
    <div>
      <label>Unique Keywords</label>
      <input type="text" placeholder="my-input" onKeyUp={handleKeyUp} />
    </div>
  );
}
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda