$.focus() not working

后端 未结 14 1102
走了就别回头了
走了就别回头了 2020-11-27 02:48

The last example of jQuery\'s focus() documentation states

$(\'#id\').focus()

should make the input focused (active). I can\'t seem to get

相关标签:
14条回答
  • 2020-11-27 03:07

    For my case I had to specify a tab index (-1 if only focusable via script)

    <div tabindex='-1'>
    <!-- ... -->
    </div>
    
    0 讨论(0)
  • 2020-11-27 03:09

    Found a solution elsewhere on the net...

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

    did not work.

    $('#id').get(0).focus();
    

    did work.

    0 讨论(0)
  • 2020-11-27 03:10

    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.

    0 讨论(0)
  • 2020-11-27 03:13

    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:

    • https://stackoverflow.com/a/43342974/1335717
    0 讨论(0)
  • 2020-11-27 03:18

    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

    0 讨论(0)
  • 2020-11-27 03:19

    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!

    0 讨论(0)
提交回复
热议问题