The last example of jQuery\'s focus() documentation states
$(\'#id\').focus()
should make the input focused (active). I can\'t seem to get
For my case I had to specify a tab index (-1
if only focusable via script)
<div tabindex='-1'>
<!-- ... -->
</div>
Found a solution elsewhere on the net...
$('#id').focus();
did not work.
$('#id').get(0).focus();
did work.
For those with the problem of not working because you used "$(element).show()". I solved it the next way:
var textbox = $("#otherOption");
textbox.show("fast", function () {
textbox[0].focus();
});
So you dont need a timer, it will execute after the show method is completed.
ADDITIONAL SOLUTION Had same issue where focus() didn't seem to work but eventually it turned out that what was needed was scrolling to the correct position:
Just in case anybody else stumbles across this question and had the same situation I had - I was trying to set the focus after clicking on another element, yet the focus didn't appear to work. It turns out I just needed an e.preventDefault();
- here's an example:
$('#recipients ul li').mousedown(function(e) {
// add recipient to list
...
// focus back onto the input
$('#message_recipient_input').focus();
// prevent the focus from leaving
e.preventDefault();
});
This helped:
If you call HTMLElement.focus() from a mousedown event handler, you must call event.preventDefault() to keep the focus from leaving the HTMLElement. Source: https://developer.mozilla.org/en/docs/Web/API/HTMLElement/focus
I realize this is old, but came across it today. None of the answers worked for me, what I did find that worked was setTimeout. I wanted my focus to be placed on the input filed of a modal, using the setTimeout worked. Hope this helps!