Setting focus on an HTML input box on page load

后端 未结 4 786
渐次进展
渐次进展 2020-12-13 11:59

I\'m trying to set the default focus on an input box when the page loads (example: google). My page is very simple, yet I can\'t figure out how to do this.

This is w

相关标签:
4条回答
  • 2020-12-13 12:14

    You could also use:

    <body onload="focusOnInput()">
        <form name="passwordForm" action="verify.php" method="post">
            <input name="passwordInput" type="password" />
        </form>
    </body>
    

    And then in your JavaScript:

    function focusOnInput() {
        document.forms["passwordForm"]["passwordInput"].focus();
    }
    
    0 讨论(0)
  • 2020-12-13 12:15

    This is one of the common issues with IE and fix for this is simple. Add .focus() twice to the input.

    Fix :-

    function FocusOnInput() {
        var element = document.getElementById('txtContactMobileNo');
        element.focus();
        setTimeout(function () { element.focus(); }, 1);
    }
    

    And call FocusOnInput() on $(document).ready(function () {.....};

    0 讨论(0)
  • 2020-12-13 12:16

    And you can use HTML5's autofocus attribute (works in all current browsers except IE9 and below). Only call your script if it's IE9 or earlier, or an older version of other browsers.

    <input type="text" name="fname" autofocus>
    
    0 讨论(0)
  • 2020-12-13 12:20

    This line:

    <input type="password" name="PasswordInput"/>
    

    should have an id attribute, like so:

    <input type="password" name="PasswordInput" id="PasswordInput"/>
    
    0 讨论(0)
提交回复
热议问题