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

前端 未结 17 1863
遇见更好的自我
遇见更好的自我 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:04

    I'm using this:

    $("form:first *:input,select,textarea").filter(":not([readonly='readonly']):not([disabled='disabled']):not([type='hidden'])").first().focus();
    
    0 讨论(0)
  • 2020-12-08 02:05

    You can also try jQuery based method:

    $(document).ready(function() {
        $('form:first *:input[type!=hidden]:first').focus();
    });
    
    0 讨论(0)
  • 2020-12-08 02:05

    Although this doesn't answer the question (requiring a common script), I though it might be useful for others to know that HTML5 introduces the 'autofocus' attribute:

    <form>
      <input type="text" name="username" autofocus>
      <input type="password" name="password">
      <input type="submit" value="Login">
    </form>
    

    Dive in to HTML5 has more information.

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

    You should be able to use clientHeight instead of checking for the display attribute, since a parent could be hiding this element:

    function setFocus() {
        var forms = document.forms || [];
            for (var i = 0; i < forms.length; i++) {
                for (var j = 0; j < forms[i].length; j++) {
                var widget = forms[i][j];
                    if ((widget && widget.domNode && widget.domNode.clientHeight > 0) && typeof widget.focus === "function")
                     && (typeof widget.disabled === "undefined" || widget.disabled === false)
                     && (typeof widget.readOnly === "undefined" || widget.readOnly === false)) {
                            widget.focus();
                            break;
                    }
                }
            }
        }   
    }
    
    0 讨论(0)
  • 2020-12-08 02:08

    If you're using the Prototype JavaScript framework then you can use the focusFirstElement method:

    Form.focusFirstElement(document.forms[0]);
    
    0 讨论(0)
  • 2020-12-08 02:10
    document.forms[0].elements[0].focus();
    

    This can be refined using a loop to eg. not focus certain types of field, disabled fields and so on. Better may be to add a class="autofocus" to the field you actually do want focused, and loop over forms[i].elements[j] looking for that className.

    Anyhow: it's not normally a good idea to do this on every page. When you focus an input the user loses the ability to eg. scroll the page from the keyboard. If unexpected, this can be annoying, so only auto-focus when you're pretty sure that using the form field is going to be what the user wants to do. ie. if you're Google.

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