How do I set the focus to the first input element in an HTML form independent from the id?

前端 未结 17 1865
遇见更好的自我
遇见更好的自我 2020-12-08 01:33

Is there a simple way to set the focus (input cursor) of a web page on the first input element (textbox, dropdownlist, ...) on loading the

相关标签:
17条回答
  • 2020-12-08 02:12

    Without third party libs, use something like

      const inputElements = parentElement.getElementsByTagName('input')
      if (inputChilds.length > 0) {
        inputChilds.item(0).focus();
      }
    

    Make sure you consider all form element tags, rule out hidden/disabled ones like in other answers and so on..

    0 讨论(0)
  • 2020-12-08 02:14

    This gets the first of any visible common input, including textareas and select boxes. This also makes sure they aren't hidden, disabled or readonly. it also allows for a target div, which I use in my software (ie, first input inside of this form).

    $("input:visible:enabled:not([readonly]),textarea:visible:enabled:not([readonly]),select:visible:enabled:not([readonly])", 
        target).first().focus();
    
    0 讨论(0)
  • 2020-12-08 02:16

    The most comprehensive jQuery expression I found working is (through the help of over here)

    $(document).ready(function() {
        $('input:visible:enabled:first').focus();
    });
    
    0 讨论(0)
  • 2020-12-08 02:18

    There's a write-up here that may be of use: Set Focus to First Input on Web Page

    0 讨论(0)
  • 2020-12-08 02:18

    This includes textareas and excludes radio buttons

    $(document).ready(function() {
        var first_input = $('input[type=text]:visible:enabled:first, textarea:visible:enabled:first')[0];
        if(first_input != undefined){ first_input.focus(); }
    });
    
    0 讨论(0)
  • 2020-12-08 02:20

    Tried lots of the answers above and they weren't working. Found this one at: http://www.kolodvor.net/2008/01/17/set-focus-on-first-field-with-jquery/#comment-1317 Thank you Kolodvor.

    $("input:text:visible:first").focus();
    
    0 讨论(0)
提交回复
热议问题