How can I set focus on an element in an HTML form using JavaScript?
Solution 1
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>
Solution 2
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 />
Solution 3
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.
Solution 4
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()
Solution 5
For plain Javascript, try the following:
window.onload = function() {
document.getElementById("TextBoxName").focus();
};
tenstar
Hi i am a computer programmer who programs web sites, intelligent agents etc.. Languages: C C++ Java Python HTML, CSS, JavaScript, PHP, XML (Web dev.) Enjoy!
Updated on January 12, 2022Comments
-
tenstar over 2 years
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>
-
peterph about 10 yearsYou'd have to scan the document using other parts of the Web API (e.g.
Document.forms
,Document.getelementsByTagName
orNode.childNodes
) and either rely on a known document structure or look for some element specific properties. -
Relevant almost 10 yearsOr the obvious answer... give it an ID ;)
-
Martin almost 10 yearsKeep in mind, this only works for setting the focus when the page first loads; it can't be used to set the focus later in response to input.
-
Fallenreaper about 9 yearsI downvoted this, because there is remotely no implication of jQuery in the base question. The OP wanted to stay purely javascript
-
Richard Rebeco about 9 yearsWell, you have reason, I went wrong, but i think that it is helpful anyway.
-
Marecky over 8 yearsAFAIK Form doesn't have "name" attribute
-
Mac over 8 yearsForms have had "names" for a long time now, and in HTML5, they still do. See w3.org/TR/html5/forms.html#the-form-element
-
Chris Love over 8 yearsI would advise against using an ID because it is over specified. Instead use the name or even a class. In that case you would use document.querySelector("[name='myText']") or document.querySelector(".myText") to get a reference to the input element.
-
Igor Mironenko about 8 years@ChrisLove Interesting advice. Why is having an id being "over specified" and what, exactly, is the problem with it? It is simpler, more precise and the code to locate it, will be slightly faster, with an ID. It sounds like the most obvious and sensible thing to do, to me - if it's possible.
-
Robert McKee about 8 years@PandaWood He is probably referring to the many editor helpers that whine about CSS if you use an id with additional selectors with a message that it is overspecified because it thinks that an id should be the the only selector required as there can only be one id, completely ignorant that HTML isn't static and the other selector may change, making the styling rule a dynamic conditional. I've only heard it from beginners in CSS. However, in this case, an id seems fair, but I would typically use another method like
$('form input:first').focus();
-
paradite about 8 yearsI am upvoting this because in projects where jQuery is already used and you elements as jQuery selection objects, it is better to be consistent instead of using vanilla JS.
-
mAAdhaTTah over 7 yearsOne of the other quirks of choosing an id is that in JavaScript, an element with an id becomes a property of the global window object. So you can actually grab the ID'd element with
window.mytext
, believe it or not. Another reason to avoid using ids if you can help it. -
Chris Love over 7 yearsSorry for the late reply. When you overspecify a CSS selector you make the code less reusable. Plus you can only have a single element in the page with that ID. What really causes the issues is CSS rules defined with an id selector. From a code maintainability it makes it more fragile because the different code you have written now becomes very tied to that ID rather than a more flexible class selector. Think about how you don't reference web sites by their IP address, but rather their domain name.
-
Toni Leigh over 7 years@ChrisLove this isn't over-specifying a CSS selector, it's setting a HTML ID attribute - specificity is a problem in the way CSS processing parses DOM selectors, not a problem with how ID and class attributes work in HTML. It's not advisable to use the same DOM selectors to attach CSS to as it is to attach JS to, meaning you can maintain the differentiation you describe
-
Toni Leigh over 7 yearsThis can be a real headache on a smaller screen if the field is off screen :-)
-
Chris Love over 7 years@toni ids are over specified because the code reference is too specific and not reusable.
-
lfrodrigues about 7 yearsI'm afraid autofocus attribute is not compatible if IOS Safari (caniuse.com/#search=autofocus) while .focus() is just incompatible with Opera Mini (caniuse.com/#search=focus)
-
Gellie Ann over 6 years@Fallenreaper Downvotes are for
egregiously sloppy, no-effort-expended post, or an answer that is clearly and perhaps dangerously incorrect
, according to stackoverflow's help center. I find this nowhere near those categories. Helping is not limited to the OP, is it? -
Fallenreaper over 6 years@GellieAnn While it is an answer, it lies outside the scope of the OPs question. There is a reason why he is using vanilla javascript, and while you can mention other frameworks and give pointers or hints to lead to one and give a reasoning why, you should still solve the answer from within the bounds of the question asked. Therefore, I stand by my downvote.
-
DeadlyChambers over 6 yearsIf you have a header bar that is fixed, you might need to use textbox.scrollIntoView(false) this simply sets the element to the bottom instead of the top.
-
ConductedClever over 5 yearsNote that testing in firefox developer tools, may not seem to work due to developer tool may keep the focus on itself. That does not mean, element.focus() not working on firefox.
-
Adam R. Turner over 5 yearsIn most modern browsers $("someelement") would be interpreted as document.getElementById even without jquery explicitly loaded. So this may very well work in vanilla js.
-
Or Choban over 5 yearsNote that if you are trying to focus from the console then it is not possible!
-
Kamil Kiełczewski about 5 yearsWhen you made components (for e.g. menu and table) and if some two elements of them has same ID and both components will be included to the same html document - then you get INVALID html. So it is not good to use ID when you create reusable components.
-
Abdull about 4 yearsDoes not work in Firefox even in 2020: bugzilla.mozilla.org/show_bug.cgi?id=277178 , stackoverflow.com/questions/5327811/…
-
nuiun over 3 yearssetting the id attribute on an input is valid and recommended to specify it's label. <form><label for="user_input">User Input</label><input type="text" name="user_input" id="user_input"></form> This pattern is especially useful when using radio buttons, because users can click the associated label text.
-
Jens Törnell about 3 yearsIt also work when using innerHTML with an input that has
autofocus
. -
Tanasos over 2 yearsThis is the proper answer for a more complex page.
-
andreyrk over 2 years@Fallenreaper that's just being pedantic
-
StefaDesign over 2 yearsautofocus attribute does work only on initial DOM page load. DOES NOT work on DOM changes (example : when you have component that will refresh DOM and apply new HTML autofocus will not work) It works with dynamic content only first time initiated. My case study was setting up focus on first result from api response so when user clicks next to load more results autofocus will not work.