输入键执行功能 [英] execute function on enter key

查看:147
本文介绍了输入键执行功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个输入,我只是想添加一个事件监听器,当我按Enter键,当输入被聚焦时激活一个功能。如何使用纯JS?



现在我有:



HTML:

 输入您的工资:< input type =textid =工资value =size = 20> 
< button id =sub> Submit< / button>

Javascript:

 code> var wage = document.getElementById(工资); 
wage.addEventListener(change,validate);

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

因此,当我点击或更改文本时,基本上激活函数validate(),但是我想调用

解决方案

你可以使用这个:

  var wage = document.getElementById(工资); 
wage.addEventListener(keydown,function(e){
if(e.keyCode === 13){//检查按下的键是否为Enter
validate(e );
}
});

函数validate(e){
var text = e.target.value;
//验证输入...
}

现场演示


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.

解决方案

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

这篇关于输入键执行功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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