简体   繁体   中英

Setting input to focus using onload

I have to set price to be focused when the page using onload.

<body style="border: solid 1px black; margin-left: auto;margin-right: auto;width: 500px;">
    <form>
        <fieldset style="margin:25px";><legend>Discount Calculator</legend>
            <div style="text-align: right; margin-right: 25%;">
            <label>Enter Price: <input onload = "thing()" type="text" name="price" id="price"></label><br><br>
            </div>
        </fieldset>
    </form>


    <script type="text/javascript">
        function thing()
        {
            document.focus()
        }

    </script>
</body>

I know I am doing something wrong. I can easily set this to be focused by using document.findElementById("price").focus() , but for this assignment I need to do it as onload. Any help would be appreciated.

If you are looking setting the focus, here is what you could do.

Also, it might be worth a read this post on what are the different load events and meaning.

Hope this helps.

 document.addEventListener("DOMContentLoaded", () => { document.querySelector("#price").focus(); }); 
 <form> <input type="text" name="dummy-1"> <input type="text" name="dummy-2"> <fieldset style="margin:25px" ;> <legend>Discount Calculator</legend> <div style="text-align: right; margin-right: 25%;"> <label>Enter Price: <input onload="thing()" type="text" name="price" id="price"> </label> <br> <br> </div> </fieldset> <input type="text" name="dummy-1"> <input type="text" name="dummy-2"> </form> 

Something like this:

document.addEventListener( 'DOMContentLoaded', function () {
    // Do stuff...
}, false );

It is an analogue of

$( document ).ready(function() {
    // Do stuff...
});

written in pure Javascript without jQuery. And one more option is to use

window.onload = function() {
  // Do stuff...
} 

thanks @mplungjan for this idea.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM