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>
If your code is:
And If you are using JQuery, You can use this too:
Keep in mind that you must draw the input first ( $(document).ready() )
Usually when we focus on a textbox, we should also scroll into view
Check if it helps.
For plain Javascript, try the following:
I used to just use this:
That said, you can just use the autofocus attribute in HTML 5.
Please note: I wanted to update this old thread showing the example asked plus the newer, easier update for those still reading this. ;)
Do this.
If your element is something like this..
Your script would be
For what it's worth, you can use the
autofocus
attribute on HTML5 compatible browsers. Works even on IE as of version 10.