How can I execute a function on pressing the enter key in an <input> field?

Here is a version of the currently accepted answer (from @MinkoGechev) with key instead of keyCode:

const wage = document.getElementById('wage');
wage.addEventListener('keydown', (e) => {
    if (e.key === 'Enter') {
        validate(e);
    }
});

function validate(e) {
    const text = e.target.value;
    //validation of the input...
}

var elem = document.getElementById("wage");
elem.onkeyup = function(e){
    if(e.keyCode == 13){
       validate();
    }
}

Working Example http://jsfiddle.net/aMgLK/


You can use this:

var wage = document.getElementById("wage");
wage.addEventListener("keydown", function (e) {
    if (e.code === "Enter") {  //checks whether the pressed key is "Enter"
        validate(e);
    }
});

function validate(e) {
    var text = e.target.value;
    //validation of the input...
}

Live demo here


var input = document.getElementById("todo-item");
input.addEventListener("keyup", function(event) {
    if (event.keyCode === 13) {
        event.preventDefault();
        document.getElementById("sub").click(); 
    }
});