edc65
edc65

Reputation: 468

Trying to set focus programmatically does not work with Firefox

I have a problem in Firefox trying to set the focus to a control using jqueryjavascript. While my specific problem is quite involved, even the simple test case below does not work for me. The input is found, its value is changed but the input is not focused.
Issue present with Firefox only

Tried with Firefox 44.0.2 on Windows 7
It works as it should with MS IE 10 and Chrome

$().ready(function() {
  $("#I").val(3);
  $("#I").focus(); // JQuery focus - does not work
  
  var ctl = document.getElementById('I')
  ctl.value='DOM';
  ctl.focus(); // DOM Native focus - does not work
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type=text id=I>

Upvotes: 3

Views: 1125

Answers (2)

Donal
Donal

Reputation: 32713

I believe there is an issue with setting focus on Firefox, there is a workaround which involves using focusout. See below:

$().ready(function() {

    $('#I').val(3);

    $('#I').focusout(function() {
        setTimeout(function() {
            $(this).focus();
        }, 0);
    });

    $('#I').focus();

})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input type="text" id="I" />

Upvotes: 1

Jai
Jai

Reputation: 74738

This style of ready event:

$().ready(function() {

Long ago deprecated and better not to use it.


You can use autofocus attribute:

$(document).ready(function() {
  $('#I').val(3);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type=text id=I autofocus>

and instead of jQuery's try triggerring the DOM .focus() event:

$(document).ready(function() {
  $('#I').val(3);
  $('#I')[0].focus();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type=text id=I>

Upvotes: 2

Related Questions