问题
I have an HTML form with several input boxes and their corresponding enter button. When I type something in the first input box and either press Enter or the button, it works fine. But if I press Enter in the other boxes it works as if it was in the first box. The buttons work OK.
Here is the code I have:
<script type="text/javascript">
function fn (num) {
alert(num);
document.getElementById(num).focus();
}
</script>
</head>
<body>
<form>
<input id="1" type="text"></input> <button onclick="fn(1);">press</button><br/>
<input id="2" type="text"></input> <button onclick="fn(2);">press</button><br/>
<input id="3" type="text"></input> <button onclick="fn(3);">press</button><br/>
</form>
Apparently this is a 'quirk' in ECMA (I have tested in FF18.0.1 and Safari 5.1.7). Is there a fix for this quirk?
One solution that I found is to add one form per input box.
<form>
<input id="1" type="text"></input> <button onclick="fn(1);">press</button><br/>
</form>
<form>
<input id="2" type="text"></input> <button onclick="fn(2);">press</button><br/>
</form>
<form>
<input id="3" type="text"></input> <button onclick="fn(3);">press</button><br/>
</form>
Is this a bug or a feature? Is there a better solution? Thanks for any suggestions.
回答1:
You'll want to use onKeyPress instead of onClick. Try this:
function myKeyPress(args) {
if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) {
// do something here (enter has been pressed)
}
else {
return false; // somehow prevents "default" form behaviors
}
}
回答2:
Try this :
$("id").keypress(function(e) {
if(e.which == 13) {
respective functions
}
});
or
<input type="text" name="q" id="q"
onkeypress="if (event.keyCode == 13) {call function}" />
来源:https://stackoverflow.com/questions/14447821/pressing-enter-with-multiple-input-boxes