Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I set focus on an element in an HTML form using JavaScript?

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> 
like image 835
tenstar Avatar asked Jul 06 '13 07:07

tenstar


People also ask

How do you focus a particular part of the HTML page in JavaScript?

The focus() function can be used to focus a particular part of the HTML page in JavaScript.

What is focus () 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()

Can we implement autofocus from JavaScript?

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.


1 Answers

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> 
like image 78
mohkhan Avatar answered Sep 22 '22 01:09

mohkhan