Mehar Mehar - 4 years ago 115
jQuery Question

jQuery focus not working on input

Want to trigger the focus event on new loaded text input field, but it is not working.
Have tried following

setTimeout(function() { jQuery("#element").focus() }, 3000);
jQuery("#element").focus();
document.getElementById('element').click();
jQuery("#element").trigger("click");

Jay Jay
Answer Source

You haven't given us the full context of what's going on in your page. Like, when are you calling this code and such. However, I think your issue may be related to trying to invoke the focus event before the control has been rendered on the page. Therefore, there are 2 things you can try to resolve the issue.

  1. Ensure that your code block isn't running before the page has finished loading (see example A)
  2. Call your code after the control you want to use it on has loaded (example B)

Example A:

$(function() {
   jQuery("#element").focus();
});

Example B:

$("#element").load(function() {
    $(this).focus();
});
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download