Home > Blockchain >  How To Trigger Button Click on Enter in JavaScript
How To Trigger Button Click on Enter in JavaScript

Time:11-24

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();
    }
})

CodePudding user response:

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

CodePudding user response:

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.

CodePudding user response:

I found the right way:

function addListAfterKeyPress(event) {
    if (inputLength() > 0 && event.key === "Enter") {
        createListElement();
    }
}
  • Related