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

151
Visualizações
Stuck using .slice to remove a character in the value of an input field

I have some HTML:

<input type="text" />

and I'm trying to make it so that when the character limit hits 12 that javascript automatically deletes the next character from the input field. See code pen here: https://codepen.io/jadedeterville/pen/NWayzpM

Here is my JS:


inputEl.addEventListener("keyup", fixLength);

function fixLength() {
  const inputElValue = inputEl.value.length;
  if (inputElValue > 11) {
    inputEl.innerHTML.slice(12);
  }
} 

I also tried inputEl.slice(12); and inputElValue.slice(12);but both of those tell me that .slice isn't a function. I tried adding the toString() but that didn't work either.

Appreciate some advice. I've been looking at this for a long time.

Thank you in advance!

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

try below code.

if (inputElValue > 11) {
  inputEl.value = inputEl.value.slice(0,12);
}
about 4 years ago · Juan Pablo Isaza Relatório

0

There are three mistakes in your script:

  1. With inputEl.innerHTML.slice(12); you're slicing anything from the start of the string up to index 12. So essentially you're clearing the whole string. If you want to keep a specific part of a string it's better to use string.substr(startIndex, length)
  2. You don't assign the result of the slice operation to the <input> textbox e.g. inputEl.innerHTML=inputEl.innerHTML.slice(12);
  3. you should use the .value property instead of .innerHTML as the latter will come up empty.

Putting it all together:

let inputEl = document.getElementById("inp");

inputEl.addEventListener("keyup", fixLength);

function fixLength() {
  const inputElValue = inputEl.value.length;
  if (inputElValue > 11) {
    inputEl.value = inputEl.value.substr(0, 12);
  }
}
<input type="text" id="inp" />

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