Prevent form submission on Enter key press

前端 未结 19 1933
失恋的感觉
失恋的感觉 2020-11-22 04:18

I have a form with two text boxes, one select drop down and one radio button. When the enter key is pressed, I want

19条回答
  •  终归单人心
    2020-11-22 04:58

    event.key === "Enter"

    More recent and much cleaner: use event.key. No more arbitrary number codes!

    NOTE: The old properties (.keyCode and .which) are Deprecated.

    const node = document.getElementsByClassName("mySelect")[0];
    node.addEventListener("keydown", function(event) {
        if (event.key === "Enter") {
            event.preventDefault();
            // Do more work
        }
    });
    

    Modern style, with lambda and destructuring

    node.addEventListener("keydown", ({key}) => {
        if (key === "Enter") // Handle press
    })
    

    Mozilla Docs

    Supported Browsers

提交回复
热议问题