简体   繁体   中英

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

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

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

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.

I found the right way:

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

Try changing "keyup" to "keypress":

button.addEventListener("keypress", function(event) {
    event.preventDefault();
    if (event.key === "Enter") {
        createListElement();
    }
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM