I have a web form with a text box in it. How do I go about setting focus to the text box by default?
Something like this:
<body onload='setFocusToTextBox()'>
so can anybody help me with it? I don't know how to set focus to the text box with JavaScript.
<script> function setFocusToTextBox(){ //What to do here } </script>
The focus() function can be used to focus a particular part of the HTML page in JavaScript.
JavaScript | Focus()It sets the element as the active element in the current document. It can be applied to one html element at a single time in a current document. The element can either be a button or a text field or a window etc. It is supported by all the browsers. Syntax: HTMLElementObject.focus()
JavaScript autofocusers (as given in the other answers here) will work but can be annoying for some users. For example, if you focus a different field while a page is still loading, the JavaScript may "help" you by moving the focus and making you type in the wrong field.
Do this.
If your element is something like this..
<input type="text" id="mytext"/>
Your script would be
<script> function setFocusToTextBox(){ document.getElementById("mytext").focus(); } </script>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With