How can I set focus on an element in an HTML form using JavaScript?
Usually when we focus on a textbox, we should also scroll into view
function setFocusToTextBox(){
var textbox = document.getElementById("yourtextbox");
textbox.focus();
textbox.scrollIntoView();
}
Check if it helps.
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>
For what it's worth, you can use the autofocus
attribute on HTML5 compatible browsers. Works even on IE as of version 10.
<input name="myinput" value="whatever" autofocus />
If your code is:
<input type="text" id="mytext"/>
And If you are using JQuery, You can use this too:
<script>
function setFocusToTextBox(){
$("#mytext").focus();
}
</script>
Keep in mind that you must draw the input first $(document).ready()