execute function on enter key

I have an input and I'd simply like to add an event listener for it to activate a function when I press enter, when the input is focused. How do I do this with pure JS?

Right now I have:

HTML:

        Enter your wage:<input type="text" id="wage" value ="" size=20>
        <button id="sub">Submit</button>

Javascript:

    var wage = document.getElementById("wage");
    wage.addEventListener("change", validate);

    var btn = document.getElementById("sub");
    btn.addEventListener("click", validate);

So basically the function validate() activates when I click OR change the text, but I want to call it by pressing enter.

Answers:

Answer

You can use this:

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

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

Live demo here

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

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

Answer

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...
}
Answer

If you change your button element to a

<input type="submit" value="Submit">

it will work with the enter button on your keyboard.

Answer

You would need something like wage.addEventListener('keydown', validate);

Your validate function would then need to check event.keyCode == 13 to determine 'enter' keypress.

Answer

Or with jQuery

$("#wage").on("keydown", function (e) {
    if (e.keyCode === 13) {  //checks whether the pressed key is "Enter"
        validate(e);
    }
});
Answer
$(document).on("keyup", function(e) {
    var key = e.which;

    if (key == 13) // the enter key ascii code
    {
        login();
    }
});
Answer
var input = document.getElementById("todo-item");
input.addEventListener("keyup", function(event) {
    if (event.keyCode === 13) {
        event.preventDefault();
        document.getElementById("sub").click(); 
    }
});

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.