Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

150
Vistas
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 Respuestas
Responde la pregunta

0

try below code.

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

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda