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

322
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

0

I found the right way:

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