How to Set Focus on Input Field using JQuery

前端 未结 3 1986
我寻月下人不归
我寻月下人不归 2020-12-15 02:34

Given the following HTML structure:


      
      
3条回答
  • 2020-12-15 02:50

    If the input happens to be in a bootstrap modal dialog, the answer is different. Copying from How to Set focus to first text input in a bootstrap modal after shown this is what is required:

    $('#myModal').on('shown.bs.modal', function () {
      $('#textareaID').focus();
    })  
    
    0 讨论(0)
  • 2020-12-15 02:54

    Justin's answer did not work for me (Chromium 18, Firefox 43.0.1). jQuery's .focus() creates visual highlight, but text cursor does not appear in the field (jquery 3.1.0).

    Inspired by https://www.sitepoint.com/jqueryhtml5-input-focus-cursor-positions/ , I added autofocus attribute to the input field and voila!

    function addfield() {
        n=$('table tr').length;
        $('table').append('<tr><td><input name=field'+n+' autofocus></td><td><input name=value'+n+'></td></tr>');
        $('input[name="aa"'+n+']').focus();
    }
    
    0 讨论(0)
  • 2020-12-15 03:00

    Try this, to set the focus to the first input field:

    $(this).parent().siblings('div.bottom').find("input.post").focus();
    
    0 讨论(0)
提交回复
热议问题