I have one text input and one button (see below). How can I use JavaScript to trigger the button's click event when the Enter key is pressed inside the text box?
我有一个文本输入和一个按钮(见下面)。当在文本框中按下Enter键时,如何使用JavaScript触发按钮的单击事件?
There is already a different submit button on my current page, so I can't simply make the button a submit button. And, I only want the Enter key to click this specific button if it is pressed from within this one text box, nothing else.
在我的当前页面上已经有了一个不同的submit按钮,所以我不能简单地将这个按钮设置为submit按钮。而且,我只想要输入键点击这个特定的按钮,如果它从这个文本框中被按下,就没有别的了。
<input type="text" id="txtSearch" />
<input type="button" id="btnSearch" value="Search" onclick="doSomething();" />
24 个解决方案
#1
1271
In jQuery, the following would work:
在jQuery中,可以使用以下方法:
$("#id_of_textbox").keyup(function(event) {
if (event.keyCode === 13) {
$("#id_of_button").click();
}
});
$("#pw").keyup(function(event) {
if (event.keyCode === 13) {
$("#myButton").click();
}
});
$("#myButton").click(function() {
alert("Button code executed.");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Username:<input id="username" type="text"><br>
Password: <input id="pw" type="password"><br>
<button id="myButton">Submit</button>
Or in plain JavaScript, the following would work:
或者用普通的JavaScript,下面的方法是:
document.getElementById("id_of_textbox")
.addEventListener("keyup", function(event) {
event.preventDefault();
if (event.keyCode === 13) {
document.getElementById("id_of_button").click();
}
});
document.getElementById("pw")
.addEventListener("keyup", function(event) {
event.preventDefault();
if (event.keyCode === 13) {
document.getElementById("myButton").click();
}
});
function buttonCode()
{
alert("Button code executed.");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Username:<input id="username" type="text"><br>
Password: <input id="pw" type="password"><br>
<button id="myButton" onclick="buttonCode()">Submit</button>
#2
355
Then just code it in!
然后把它编码进去!
<input type = "text"
id = "txtSearch"
onkeydown = "if (event.keyCode == 13)
document.getElementById('btnSearch').click()"
/>
<input type = "button"
id = "btnSearch"
value = "Search"
onclick = "doSomething();"
/>
#3
164
Figured this out:
算出来:
<input type="text" id="txtSearch" onkeypress="return searchKeyPress(event);" />
<input type="button" id="btnSearch" Value="Search" onclick="doSomething();" />
<script>
function searchKeyPress(e)
{
// look for window.event in case event isn't passed in
e = e || window.event;
if (e.keyCode == 13)
{
document.getElementById('btnSearch').click();
return false;
}
return true;
}
</script>
#4
74
Make the button a submit element, so it'll be automatic.
将按钮设置为submit元素,因此它将是自动的。
<input type = "submit"
id = "btnSearch"
value = "Search"
onclick = "return doSomething();"
/>
Note that you'll need a <form>
element containing the input fields to make this work (thanks Sergey Ilinsky).
注意,您将需要一个包含输入字段的
It's not a good practice to redefine standard behaviour, the Enter key should always call the submit button on a form.
重新定义标准行为不是一个好的实践,输入键应该始终调用表单上的submit按钮。
#5
66
Since no one has used addEventListener
yet, here is my version. Given the elements:
由于还没有人使用addEventListener,下面是我的版本。考虑到元素:
<input type = "text" id = "txt" />
<input type = "button" id = "go" />
I would use the following:
我将使用以下内容:
var go = document.getElementById("go");
var txt = document.getElementById("txt");
txt.addEventListener("keypress", function(event) {
event.preventDefault();
if (event.keyCode == 13)
go.click();
});
This allows you to change the event type and action separately while keeping the HTML clean.
这允许您在保持HTML干净的同时,分别更改事件类型和操作。
Note that it's probably worthwhile to make sure this is outside of a
<form>
because when I enclosed these elements in them pressing Enter submitted the form and reloaded the page. Took me a few blinks to discover.注意,确保它在
Addendum: Thanks to a comment by @ruffin, I've added the missing event handler and a
preventDefault
to allow this code to (presumably) work inside a form as well. (I will get around to testing this, at which point I will remove the bracketed content.)附录:感谢@ruffin的评论,我添加了丢失的事件处理程序和preventDefault,以允许这些代码在窗体中工作。(我将着手测试它,然后删除括号内的内容。)
#6
54
In plain JavaScript,
在纯JavaScript,
if (document.layers) {
document.captureEvents(Event.KEYDOWN);
}
document.onkeydown = function (evt) {
var keyCode = evt ? (evt.which ? evt.which : evt.keyCode) : event.keyCode;
if (keyCode == 13) {
// For Enter.
// Your function here.
}
if (keyCode == 27) {
// For Escape.
// Your function here.
} else {
return true;
}
};
I noticed that the reply is given in jQuery only, so I thought of giving something in plain JavaScript as well.
我注意到这个回复只在jQuery中给出,所以我想用普通的JavaScript来做一些事情。
#7
19
One basic trick you can use for this that I haven't seen fully mentioned. If you want to do an ajax action, or some other work on Enter but don't want to actually submit a form you can do this:
你可以用一个基本的技巧来解决这个问题,我还没完全提到。如果你想做一个ajax动作,或者在Enter上做一些其他的工作,但又不想提交一个表单,你可以这样做:
<form onsubmit="Search();" action="javascript:void(0);">
<input type="text" id="searchCriteria" placeholder="Search Criteria"/>
<input type="button" onclick="Search();" value="Search" id="searchBtn"/>
</form>
Setting action="javascript:void(0);" like this is a shortcut for preventing default behavior essentially. In this case a method is called whether you hit enter or click the button and an ajax call is made to load some data.
设置动作="javascript:void(0);"这样的设置实际上是防止默认行为的快捷方式。在这种情况下,无论单击enter还是单击按钮,都会调用一个方法,并调用ajax来加载一些数据。
#8
13
Try it:
试一试:
<input type="text" id="txtSearch"/>
<input type="button" id="btnSearch" Value="Search"/>
<script>
window.onload = function() {
document.getElementById('txtSearch').onkeypress = function searchKeyPress(event) {
if (event.keyCode == 13) {
document.getElementById('btnSearch').click();
}
};
document.getElementById('btnSearch').onclick =doSomething;
}
</script>
#9
12
To trigger a search every time the enter key is pressed, use this:
要在每次按下enter键时触发搜索,请使用以下命令:
$(document).keypress(function(event) {
var keycode = (event.keyCode ? event.keyCode : event.which);
if (keycode == '13') {
$('#btnSearch').click();
}
}
#10
11
onkeydown="javascript:if (event.which || event.keyCode){if ((event.which == 13) || (event.keyCode == 13)) {document.getElementById('btnSearch').click();}};"
This is just something I have from a somewhat recent project... I found it on the net, and I have no idea if there's a better way or not in plain old JavaScript.
这是我最近一个项目的成果……我在网上找到了它,我不知道是否有更好的方法或者不是用普通的JavaScript。
#11
9
Although, I'm pretty sure that as long as there is only one field in the form and one submit button, hitting enter should submit the form, even if there is another form on the page.
虽然,我很确定,只要表单中只有一个字段和一个提交按钮,点击enter就应该提交表单,即使页面上还有另一个表单。
You can then capture the form onsubmit with js and do whatever validation or callbacks you want.
然后,您可以用js捕获onsubmit表单,并执行任何您想要的验证或回调。
#12
9
Nobody noticed the html attibute "accesskey" which is available since a while.
没有人注意到html attibute的“accesskey”。
This is a no javascript way to keyboard shortcuts stuffs.
这不是使用javascript实现快捷键的方法。
The accesskey attributes shortcuts on MDN
在MDN上的accesskey属性快捷方式。
Intented to be used like this. The html attribute itself is enough, howewer we can change the placeholder or other indicator depending of the browser and os. The script is a untested scratch approach to give an idea. You may want to use a browser library detector like the tiny bowser
本打算这样使用。html属性本身就足够了,但是我们可以根据浏览器和os更改占位符或其他指示符。这个脚本是一个没有经过测试的scratch方法来给出一个想法。您可能想要使用浏览器库检测器,比如小型的bowser
let client = navigator.userAgent.toLowerCase();
isLinux = client.indexOf("linux") > -1;
isWin = client.indexOf("windows") > -1;
isMac = client.indexOf("apple") > -1;
isFirefox = client.indexOf("firefox") > -1;
isWebkit = client.indexOf("webkit") > -1;
isOpera = client.indexOf("opera") > -1;
input = document.getElementById('guestInput');
if(isFirefox) {
input.setAttribute("placeholder", "Access keys: ALT+SHIFT+Z");
} else if (isWin) {
input.setAttribute("placeholder", "Access keys: ALT+Z");
} else if (isMac) {
input.setAttribute("placeholder", "Access keys: CTRL+ALT+Z");
} else if (isOpera) {
input.setAttribute("placeholder", "Shortcut: SHIFT+ESCAPE->Z");
} else {'Point me to operate...'}
<input type="text" id="guestInput" accesskey="z" placeholder="Acces shortcut:"></input>
#13
8
This is a solution for all the YUI lovers out there:
这是所有YUI爱好者的一个解决方案:
Y.on('keydown', function() {
if(event.keyCode == 13){
Y.one("#id_of_button").simulate("click");
}
}, '#id_of_textbox');
In this special case I did have better results using YUI for triggering DOM objects that have been injected with button functionality - but this is another story...
在这个特殊的例子中,我确实在使用YUI触发注入按钮功能的DOM对象时得到了更好的结果——但这是另一个故事……
#14
7
This onchange attempt is close, but misbehaves with respect to browser back then forward (on Safari 4.0.5 and Firefox 3.6.3), so ultimately, I wouldn't recommend it.
这个onchange尝试很接近,但是它在浏览器上的错误行为(在Safari 4.0.5和Firefox 3.6.3上),所以最终我不会推荐它。
<input type="text" id="txtSearch" onchange="doSomething();" />
<input type="button" id="btnSearch" value="Search" onclick="doSomething();" />
#15
7
In Angular2:
在Angular2:
(keyup.enter)="doSomething()"
If you don't want some visual feedback in the button, it's a good design to not reference the button but rather directly invoke the controller.
如果您不希望在按钮中看到一些视觉反馈,那么最好不要引用按钮,而是直接调用控制器。
Also, the id isn't needed - another NG2 way of separating between the view and the model.
另外,不需要id,这是另一个在视图和模型之间分离的NG2方法。
#16
6
event.returnValue = false
Use it when handling the event or in the function your event handler calls.
当处理事件或在事件处理程序调用的函数中使用它。
It works in Internet Explorer and Opera at least.
它至少在Internet Explorer和Opera中工作。
#17
6
For jquery mobile I had to do
对于jquery mobile,我必须这么做
$('#id_of_textbox').live("keyup", function(event) {
if(event.keyCode == '13'){
$('#id_of_button').click();
}
});
#18
6
This in-case you want also diable the enter button from Posting to server and execute the Js script.
在这种情况下,您还需要将enter按钮从post转到服务器并执行Js脚本。
<input type="text" id="txtSearch" onkeydown="if (event.keyCode == 13)
{document.getElementById('btnSearch').click(); return false;}"/>
<input type="button" id="btnSearch" value="Search" onclick="doSomething();" />
#19
5
To add a completely plain JavaScript solution that addressed @icedwater's issue with form submission, here's a complete solution with form
.
要添加一个完全简单的JavaScript解决方案来解决@icedwater的表单提交问题,这里有一个完整的表单解决方案。
NOTE: This is for "modern browsers", including IE9+. The IE8 version isn't much more complicated, and can be learned here.
注意:这是针对“现代浏览器”的,包括IE9+。IE8版本并不复杂,可以在这里学到。
Fiddle: https://jsfiddle.net/rufwork/gm6h25th/1/
小提琴:https://jsfiddle.net/rufwork/gm6h25th/1/
HTML
<body>
<form>
<input type="text" id="txt" />
<input type="button" id="go" value="Click Me!" />
<div id="outige"></div>
</form>
</body>
JavaScript
// The document.addEventListener replicates $(document).ready() for
// modern browsers (including IE9+), and is slightly more robust than `onload`.
// More here: https://*.com/a/21814964/1028230
document.addEventListener("DOMContentLoaded", function() {
var go = document.getElementById("go"),
txt = document.getElementById("txt"),
outige = document.getElementById("outige");
// Note that jQuery handles "empty" selections "for free".
// Since we're plain JavaScripting it, we need to make sure this DOM exists first.
if (txt && go) {
txt.addEventListener("keypress", function (e) {
if (event.keyCode === 13) {
go.click();
e.preventDefault(); // <<< Most important missing piece from icedwater
}
});
go.addEventListener("click", function () {
if (outige) {
outige.innerHTML += "Clicked!<br />";
}
});
}
});
#20
4
document.onkeypress = function (e) {
e = e || window.event;
var charCode = (typeof e.which == "number") ? e.which : e.keyCode;
if (charCode == 13) {
// Do something here
printResult();
}
};
Heres my two cents. I am working on an app for Windows 8 and want the button to register a click event when I press the Enter button. I am doing this in JS. I tried a couple of suggestions, but had issues. This works just fine.
这是我的两个美分。我正在为Windows 8开发一个应用程序,并希望按钮在我按下Enter按钮时注册一个单击事件。我用JS做这个。我试了几个建议,但有问题。这样做挺好。
#21
4
Use keypress
and event.key
with modern JS!
const textbox = document.getElementById("txtSearch");
textbox.addEventListener("keypress", function onEvent(event) {
if (event.key === "Enter") {
document.getElementById("btnSearch").click();
}
});
Mozilla文档
支持的浏览器
#22
3
To do it with jQuery:
用jQuery实现:
$("#txtSearch").on("keyup", function (event) {
if (event.keyCode==13) {
$("#btnSearch").get(0).click();
}
});
To do it with normal JavaScript:
用普通JavaScript实现:
document.getElementById("txtSearch").addEventListener("keyup", function (event) {
if (event.keyCode==13) {
document.getElementById("#btnSearch").click();
}
});
#23
1
For those who may like brevity and modern js approach.
对于那些喜欢简洁和现代js方法的人来说。
input.addEventListener('keydown', (e) => {if (e.keyCode == 13) doSomething()});
where input is a variable containing your input element.
输入是包含输入元素的变量。
#24
-3
This also might help, a small JavaScript function, which works fine:
这也可能会有帮助,一个小的JavaScript函数,它运行良好:
<script type="text/javascript">
function blank(a) { if(a.value == a.defaultValue) a.value = ""; }
function unblank(a) { if(a.value == "") a.value = a.defaultValue; }
</script>
<input type="text" value="email goes here" onfocus="blank(this)" onblur="unblank(this)" />
I know this question is solved, but I just found something, which can be helpful for others.
我知道这个问题已经解决了,但是我发现了一些对别人有用的东西。
#1
1271
In jQuery, the following would work:
在jQuery中,可以使用以下方法:
$("#id_of_textbox").keyup(function(event) {
if (event.keyCode === 13) {
$("#id_of_button").click();
}
});
$("#pw").keyup(function(event) {
if (event.keyCode === 13) {
$("#myButton").click();
}
});
$("#myButton").click(function() {
alert("Button code executed.");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Username:<input id="username" type="text"><br>
Password: <input id="pw" type="password"><br>
<button id="myButton">Submit</button>
Or in plain JavaScript, the following would work:
或者用普通的JavaScript,下面的方法是:
document.getElementById("id_of_textbox")
.addEventListener("keyup", function(event) {
event.preventDefault();
if (event.keyCode === 13) {
document.getElementById("id_of_button").click();
}
});
document.getElementById("pw")
.addEventListener("keyup", function(event) {
event.preventDefault();
if (event.keyCode === 13) {
document.getElementById("myButton").click();
}
});
function buttonCode()
{
alert("Button code executed.");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Username:<input id="username" type="text"><br>
Password: <input id="pw" type="password"><br>
<button id="myButton" onclick="buttonCode()">Submit</button>
#2
355
Then just code it in!
然后把它编码进去!
<input type = "text"
id = "txtSearch"
onkeydown = "if (event.keyCode == 13)
document.getElementById('btnSearch').click()"
/>
<input type = "button"
id = "btnSearch"
value = "Search"
onclick = "doSomething();"
/>
#3
164
Figured this out:
算出来:
<input type="text" id="txtSearch" onkeypress="return searchKeyPress(event);" />
<input type="button" id="btnSearch" Value="Search" onclick="doSomething();" />
<script>
function searchKeyPress(e)
{
// look for window.event in case event isn't passed in
e = e || window.event;
if (e.keyCode == 13)
{
document.getElementById('btnSearch').click();
return false;
}
return true;
}
</script>
#4
74
Make the button a submit element, so it'll be automatic.
将按钮设置为submit元素,因此它将是自动的。
<input type = "submit"
id = "btnSearch"
value = "Search"
onclick = "return doSomething();"
/>
Note that you'll need a <form>
element containing the input fields to make this work (thanks Sergey Ilinsky).
注意,您将需要一个包含输入字段的
It's not a good practice to redefine standard behaviour, the Enter key should always call the submit button on a form.
重新定义标准行为不是一个好的实践,输入键应该始终调用表单上的submit按钮。
#5
66
Since no one has used addEventListener
yet, here is my version. Given the elements:
由于还没有人使用addEventListener,下面是我的版本。考虑到元素:
<input type = "text" id = "txt" />
<input type = "button" id = "go" />
I would use the following:
我将使用以下内容:
var go = document.getElementById("go");
var txt = document.getElementById("txt");
txt.addEventListener("keypress", function(event) {
event.preventDefault();
if (event.keyCode == 13)
go.click();
});
This allows you to change the event type and action separately while keeping the HTML clean.
这允许您在保持HTML干净的同时,分别更改事件类型和操作。
Note that it's probably worthwhile to make sure this is outside of a
<form>
because when I enclosed these elements in them pressing Enter submitted the form and reloaded the page. Took me a few blinks to discover.注意,确保它在
Addendum: Thanks to a comment by @ruffin, I've added the missing event handler and a
preventDefault
to allow this code to (presumably) work inside a form as well. (I will get around to testing this, at which point I will remove the bracketed content.)附录:感谢@ruffin的评论,我添加了丢失的事件处理程序和preventDefault,以允许这些代码在窗体中工作。(我将着手测试它,然后删除括号内的内容。)
#6
54
In plain JavaScript,
在纯JavaScript,
if (document.layers) {
document.captureEvents(Event.KEYDOWN);
}
document.onkeydown = function (evt) {
var keyCode = evt ? (evt.which ? evt.which : evt.keyCode) : event.keyCode;
if (keyCode == 13) {
// For Enter.
// Your function here.
}
if (keyCode == 27) {
// For Escape.
// Your function here.
} else {
return true;
}
};
I noticed that the reply is given in jQuery only, so I thought of giving something in plain JavaScript as well.
我注意到这个回复只在jQuery中给出,所以我想用普通的JavaScript来做一些事情。
#7
19
One basic trick you can use for this that I haven't seen fully mentioned. If you want to do an ajax action, or some other work on Enter but don't want to actually submit a form you can do this:
你可以用一个基本的技巧来解决这个问题,我还没完全提到。如果你想做一个ajax动作,或者在Enter上做一些其他的工作,但又不想提交一个表单,你可以这样做:
<form onsubmit="Search();" action="javascript:void(0);">
<input type="text" id="searchCriteria" placeholder="Search Criteria"/>
<input type="button" onclick="Search();" value="Search" id="searchBtn"/>
</form>
Setting action="javascript:void(0);" like this is a shortcut for preventing default behavior essentially. In this case a method is called whether you hit enter or click the button and an ajax call is made to load some data.
设置动作="javascript:void(0);"这样的设置实际上是防止默认行为的快捷方式。在这种情况下,无论单击enter还是单击按钮,都会调用一个方法,并调用ajax来加载一些数据。
#8
13
Try it:
试一试:
<input type="text" id="txtSearch"/>
<input type="button" id="btnSearch" Value="Search"/>
<script>
window.onload = function() {
document.getElementById('txtSearch').onkeypress = function searchKeyPress(event) {
if (event.keyCode == 13) {
document.getElementById('btnSearch').click();
}
};
document.getElementById('btnSearch').onclick =doSomething;
}
</script>
#9
12
To trigger a search every time the enter key is pressed, use this:
要在每次按下enter键时触发搜索,请使用以下命令:
$(document).keypress(function(event) {
var keycode = (event.keyCode ? event.keyCode : event.which);
if (keycode == '13') {
$('#btnSearch').click();
}
}
#10
11
onkeydown="javascript:if (event.which || event.keyCode){if ((event.which == 13) || (event.keyCode == 13)) {document.getElementById('btnSearch').click();}};"
This is just something I have from a somewhat recent project... I found it on the net, and I have no idea if there's a better way or not in plain old JavaScript.
这是我最近一个项目的成果……我在网上找到了它,我不知道是否有更好的方法或者不是用普通的JavaScript。
#11
9
Although, I'm pretty sure that as long as there is only one field in the form and one submit button, hitting enter should submit the form, even if there is another form on the page.
虽然,我很确定,只要表单中只有一个字段和一个提交按钮,点击enter就应该提交表单,即使页面上还有另一个表单。
You can then capture the form onsubmit with js and do whatever validation or callbacks you want.
然后,您可以用js捕获onsubmit表单,并执行任何您想要的验证或回调。
#12
9
Nobody noticed the html attibute "accesskey" which is available since a while.
没有人注意到html attibute的“accesskey”。
This is a no javascript way to keyboard shortcuts stuffs.
这不是使用javascript实现快捷键的方法。
The accesskey attributes shortcuts on MDN
在MDN上的accesskey属性快捷方式。
Intented to be used like this. The html attribute itself is enough, howewer we can change the placeholder or other indicator depending of the browser and os. The script is a untested scratch approach to give an idea. You may want to use a browser library detector like the tiny bowser
本打算这样使用。html属性本身就足够了,但是我们可以根据浏览器和os更改占位符或其他指示符。这个脚本是一个没有经过测试的scratch方法来给出一个想法。您可能想要使用浏览器库检测器,比如小型的bowser
let client = navigator.userAgent.toLowerCase();
isLinux = client.indexOf("linux") > -1;
isWin = client.indexOf("windows") > -1;
isMac = client.indexOf("apple") > -1;
isFirefox = client.indexOf("firefox") > -1;
isWebkit = client.indexOf("webkit") > -1;
isOpera = client.indexOf("opera") > -1;
input = document.getElementById('guestInput');
if(isFirefox) {
input.setAttribute("placeholder", "Access keys: ALT+SHIFT+Z");
} else if (isWin) {
input.setAttribute("placeholder", "Access keys: ALT+Z");
} else if (isMac) {
input.setAttribute("placeholder", "Access keys: CTRL+ALT+Z");
} else if (isOpera) {
input.setAttribute("placeholder", "Shortcut: SHIFT+ESCAPE->Z");
} else {'Point me to operate...'}
<input type="text" id="guestInput" accesskey="z" placeholder="Acces shortcut:"></input>
#13
8
This is a solution for all the YUI lovers out there:
这是所有YUI爱好者的一个解决方案:
Y.on('keydown', function() {
if(event.keyCode == 13){
Y.one("#id_of_button").simulate("click");
}
}, '#id_of_textbox');
In this special case I did have better results using YUI for triggering DOM objects that have been injected with button functionality - but this is another story...
在这个特殊的例子中,我确实在使用YUI触发注入按钮功能的DOM对象时得到了更好的结果——但这是另一个故事……
#14
7
This onchange attempt is close, but misbehaves with respect to browser back then forward (on Safari 4.0.5 and Firefox 3.6.3), so ultimately, I wouldn't recommend it.
这个onchange尝试很接近,但是它在浏览器上的错误行为(在Safari 4.0.5和Firefox 3.6.3上),所以最终我不会推荐它。
<input type="text" id="txtSearch" onchange="doSomething();" />
<input type="button" id="btnSearch" value="Search" onclick="doSomething();" />
#15
7
In Angular2:
在Angular2:
(keyup.enter)="doSomething()"
If you don't want some visual feedback in the button, it's a good design to not reference the button but rather directly invoke the controller.
如果您不希望在按钮中看到一些视觉反馈,那么最好不要引用按钮,而是直接调用控制器。
Also, the id isn't needed - another NG2 way of separating between the view and the model.
另外,不需要id,这是另一个在视图和模型之间分离的NG2方法。
#16
6
event.returnValue = false
Use it when handling the event or in the function your event handler calls.
当处理事件或在事件处理程序调用的函数中使用它。
It works in Internet Explorer and Opera at least.
它至少在Internet Explorer和Opera中工作。
#17
6
For jquery mobile I had to do
对于jquery mobile,我必须这么做
$('#id_of_textbox').live("keyup", function(event) {
if(event.keyCode == '13'){
$('#id_of_button').click();
}
});
#18
6
This in-case you want also diable the enter button from Posting to server and execute the Js script.
在这种情况下,您还需要将enter按钮从post转到服务器并执行Js脚本。
<input type="text" id="txtSearch" onkeydown="if (event.keyCode == 13)
{document.getElementById('btnSearch').click(); return false;}"/>
<input type="button" id="btnSearch" value="Search" onclick="doSomething();" />
#19
5
To add a completely plain JavaScript solution that addressed @icedwater's issue with form submission, here's a complete solution with form
.
要添加一个完全简单的JavaScript解决方案来解决@icedwater的表单提交问题,这里有一个完整的表单解决方案。
NOTE: This is for "modern browsers", including IE9+. The IE8 version isn't much more complicated, and can be learned here.
注意:这是针对“现代浏览器”的,包括IE9+。IE8版本并不复杂,可以在这里学到。
Fiddle: https://jsfiddle.net/rufwork/gm6h25th/1/
小提琴:https://jsfiddle.net/rufwork/gm6h25th/1/
HTML
<body>
<form>
<input type="text" id="txt" />
<input type="button" id="go" value="Click Me!" />
<div id="outige"></div>
</form>
</body>
JavaScript
// The document.addEventListener replicates $(document).ready() for
// modern browsers (including IE9+), and is slightly more robust than `onload`.
// More here: https://*.com/a/21814964/1028230
document.addEventListener("DOMContentLoaded", function() {
var go = document.getElementById("go"),
txt = document.getElementById("txt"),
outige = document.getElementById("outige");
// Note that jQuery handles "empty" selections "for free".
// Since we're plain JavaScripting it, we need to make sure this DOM exists first.
if (txt && go) {
txt.addEventListener("keypress", function (e) {
if (event.keyCode === 13) {
go.click();
e.preventDefault(); // <<< Most important missing piece from icedwater
}
});
go.addEventListener("click", function () {
if (outige) {
outige.innerHTML += "Clicked!<br />";
}
});
}
});
#20
4
document.onkeypress = function (e) {
e = e || window.event;
var charCode = (typeof e.which == "number") ? e.which : e.keyCode;
if (charCode == 13) {
// Do something here
printResult();
}
};
Heres my two cents. I am working on an app for Windows 8 and want the button to register a click event when I press the Enter button. I am doing this in JS. I tried a couple of suggestions, but had issues. This works just fine.
这是我的两个美分。我正在为Windows 8开发一个应用程序,并希望按钮在我按下Enter按钮时注册一个单击事件。我用JS做这个。我试了几个建议,但有问题。这样做挺好。
#21
4
Use keypress
and event.key
with modern JS!
const textbox = document.getElementById("txtSearch");
textbox.addEventListener("keypress", function onEvent(event) {
if (event.key === "Enter") {
document.getElementById("btnSearch").click();
}
});
Mozilla文档
支持的浏览器
#22
3
To do it with jQuery:
用jQuery实现:
$("#txtSearch").on("keyup", function (event) {
if (event.keyCode==13) {
$("#btnSearch").get(0).click();
}
});
To do it with normal JavaScript:
用普通JavaScript实现:
document.getElementById("txtSearch").addEventListener("keyup", function (event) {
if (event.keyCode==13) {
document.getElementById("#btnSearch").click();
}
});
#23
1
For those who may like brevity and modern js approach.
对于那些喜欢简洁和现代js方法的人来说。
input.addEventListener('keydown', (e) => {if (e.keyCode == 13) doSomething()});
where input is a variable containing your input element.
输入是包含输入元素的变量。
#24
-3
This also might help, a small JavaScript function, which works fine:
这也可能会有帮助,一个小的JavaScript函数,它运行良好:
<script type="text/javascript">
function blank(a) { if(a.value == a.defaultValue) a.value = ""; }
function unblank(a) { if(a.value == "") a.value = a.defaultValue; }
</script>
<input type="text" value="email goes here" onfocus="blank(this)" onblur="unblank(this)" />
I know this question is solved, but I just found something, which can be helpful for others.
我知道这个问题已经解决了,但是我发现了一些对别人有用的东西。