I have an input field and a login button. I want to allow users to hit the \"enter\" key to click the button when the input field is focused. How would I do this with jQuery?<
You don't need jQuery for this, just change the button to type="submit"
:
<input type="text" size="10" id="loginUserID" name="username">
<input type="submit" value="Login" name="loginBtn" id="loginBtn">
Then the <form>
will submit all by itself when you hit Enter inside the text input.
The answer does not work when the trigger is somewhere attached in asp.net code adn not in js or jquery. What works fine is setting the focus on the button. In your case replace my named (sharepoint generated) fields with your login fields
<script type ="text/javascript">
$(document).ready(function () {
var zoekveld = $( "input[name='ctl00$m$g_02abe20b_56ca_4744_a694_5bc31dd14f49$ctl02']" );
var loep = $( "input[name='ctl00$m$g_02abe20b_56ca_4744_a694_5bc31dd14f49$ctl04']" );
zoekveld.keypress(function(e){
//alert("gevonden op name");
var key = e.which;
if(key == 13){
//alert("op enter geklikt");
loep.focus();
}
});
});
</script>
The accepted answer, and most of the others, give for granted that the click() action might end event handling by submitting the form and switching to another page, or that there is not a submit somewhere on the form, so they omit stopping the event chain, but this might not be the case.
Don't forget to call e.preventDefault()
before calling click()
on the target button. Or else, the first button on the form will still fire on enter, in addition to your click!
$('#loginUserID').keypress(function(event) {
if(event.keyCode == 13) {
e.preventDefault(); // Stop the default behaviour
$('#loginBtn').click();
}
});
$('#loginUserID').keypress(function(event){
if(event.keyCode == 13){
$('#loginBtn').click();
}
});
Demo: http://jsfiddle.net/Bhf5a/
If they're in the same form and you change the button to be type="submit"
you should find it happens automatically, but anyway...
$(document).ready(function() {
$('#loginUserID').keypress(function(e){
if(e.which === 13)
$('#loginBtn').click();
});
});
(Or you may prefer .keyup
or .keydown
.)