如何在< input>中按下Enter键来执行功能场地? [英] How can I execute a function on pressing the enter key in an <input> field?

查看:78
本文介绍了如何在< input>中按下Enter键来执行功能场地?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个输入,我只是想添加一个事件侦听器,以便在输入聚焦时按Enter来激活一个功能.我该如何使用纯JS?

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?

现在我有:

HTML:

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

JavaScript:

JavaScript:

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

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

因此基本上,当我单击或更改文本时,功能validate()会激活,但是我想通过按Enter来调用它.

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

推荐答案

您可以使用此

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

这篇关于如何在&lt; input&gt;中按下Enter键来执行功能场地?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆