execute function on enter key

2019-01-06 20:39发布

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.

7条回答
淡お忘
2楼-- · 2019-01-06 21:35
var elem = document.getElementById("wage");
elem.onkeyup = function(e){
    if(e.keyCode == 13){
       validate();
    }
}

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

查看更多
登录 后发表回答