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

323
Vistas
How To Trigger Button Click on Enter in JavaScript

The addEventListener on click is working but on event.keypress or event.code dont. I can't understand why? I tried to add key code, with and without "", tried to remove default, with indication of object length (inputLength() > 0 && event.code "Enter") etc.. still nothing. Can't find a solution in existent threads((.

var button = document.getElementById("enter");
var input = document.getElementById("userinput");
var ul = document.querySelector("ul");


function inputLength() {
    return input.value.length;
}

function createListElement() {
    var li = document.createElement("li");
    li.appendChild(document.createTextNode(input.value));
    ul.appendChild(li);
    input.value = "";
}

button.addEventListener("click", function() {
    if (inputLength() > 0) {
        createListElement();
    }
})

button.addEventListener("keyup", function(event) {
    event.preventDefault();
    if (event.key === "Enter") {
        createListElement();
    }
})
about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

For addEventListener, you may need a third argument false e.g. button.addEventListener("click",function(){blah},false);

about 4 years ago · Juan Pablo Isaza Denunciar

0

button.addEventListener("keyup", function(event) {
  // Number 13 is the "Enter" key on the keyboard
  if (event.key === 'Enter') {
    // Cancel the default action, if needed
    event.preventDefault();
    //now do what you want to do.
    createListElement();  
}
} false);

I just want to say, that you should definetly use google more often. I was able to find the anwser after 1 google search. Anyways hope this helps.

about 4 years ago · Juan Pablo Isaza Denunciar

0

I found the right way:

function addListAfterKeyPress(event) {
    if (inputLength() > 0 && event.key === "Enter") {
        createListElement();
    }
}
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