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>
This question is related to
javascript
html
textbox
focus
window.onload is to put focus initially onblur is to put focus while you click outside of the textarea,or avoid text area blur
<textarea id="focus"></textarea>
<script>
var mytexarea=document.getElementById("focus");
window.onload=function()
{
mytexarea.focus();
}
mytextarea.onblur=function(){
mytextarea.focus();
}
</script>
If your <input>
or <textarea>
has attribute id=mytext
then use
mytext.focus();
function setFocusToTextBox() {_x000D_
mytext.focus();_x000D_
}
_x000D_
<body onload='setFocusToTextBox()'>_x000D_
<form>_x000D_
<input type="text" id="mytext"/>_x000D_
</form>_x000D_
</body>
_x000D_
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()
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.
As mentioned earlier, document.forms works too.
function setFocusToTextBox( _element ) {
document.forms[ 'myFormName' ].elements[ _element ].focus();
}
setFocusToTextBox( 0 );
// sets focus on first element of the form
I used to just use this:
<html>
<head>
<script type="text/javascript">
function focusFieldOne() {
document.FormName.FieldName.focus();
}
</script>
</head>
<body onLoad="focusFieldOne();">
<form name="FormName">
Field <input type="text" name="FieldName">
</form>
</body>
</html>
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. ;)
For plain Javascript, try the following:
window.onload = function() {
document.getElementById("TextBoxName").focus();
};
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 />
Source: Stackoverflow.com