I am trying to set the focus to a button while the user presses the Enter key in the text box. But it is not working. I am using the Internet Explorer 8 browser. Am I missing something?
$("input.Box").live('keydown', function(e) {
if (e.keyCode == 13) {
e.preventDefault();
$("#button").focus(); // Not working?
}
});
The reason that's not working is simply because it's not stealing focus from the dev console. If you run the following code in your console and then quickly click in your browser window after, you will see it focus the search box: setTimeout(function() { $('input[name="q"]'). focus() }, 3000);
JavaScript | Focus() It sets the element as the active element in the current document. It can be applied to one html element at a single time in a current document. The element can either be a button or a text field or a window etc. It is supported by all the browsers.
The problem is that IE is not able to respond quickly enough, so you need to add a small delay between when the live
function is entered, and when .focus()
is called. So, replace
$("#button").focus();
with
setTimeout(function () {
$('#button').focus();
}, 100);
This, in conjunction with using e.which
with e.keyCode
as Blender suggested should fix your issue.
Microsoft decided that they don't like e.keyCode
and instead have their own syntax, e.which
.
You have to check for both:
$("input.Box").live('keydown', function(e) {
var keyCode = (window.event) ? e.which : e.keyCode;
if (keyCode == 13)
e.preventDefault();
$("#button").focus(); // Not working?
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With