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

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

    Putting this code at the end of your body tag will focus the first visible, non-hidden enabled element on the screen automatically. It will handle most cases I can come up with on short notice.

    <script>
        (function(){
            var forms = document.forms || [];
            for(var i = 0; i < forms.length; i++){
                for(var j = 0; j < forms[i].length; j++){
                    if(!forms[i][j].readonly != undefined && forms[i][j].type != "hidden" && forms[i][j].disabled != true && forms[i][j].style.display != 'none'){
                        forms[i][j].focus();
                        return;
                    }
                }
            }
        })();
    </script>
    
    0 讨论(0)
  • 2020-12-08 02:21

    With AngularJS :

    angular.element('#Element')[0].focus();
    
    0 讨论(0)
  • 2020-12-08 02:24

    For those who use JSF2.2+ and cannot pass autofocus as an attribute without value to it, use this:

     p:autofocus="true"
    

    And add it to the namespace p (Also often used pt. Whatever you like).

    <html ... xmlns:p="http://java.sun.com/jsf/passthrough">
    
    0 讨论(0)
  • 2020-12-08 02:24

    without jquery, e.g. with regular javascript:

    document.querySelector('form input:not([type=hidden])').focus()
    

    works on Safari but not Chrome 75 (april 2019)

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

    You also need to skip any hidden inputs.

    for (var i = 0; document.forms[0].elements[i].type == 'hidden'; i++);
    document.forms[0].elements[i].focus();
    
    0 讨论(0)
提交回复
热议问题