HTML DOM Document getElementById()The getElementById() method returns an element with a specified value. The getElementById() method returns null if the element does not exist. The getElementById() method is one of the most common methods in the HTML DOM.
focus() Javascript focus() methods helps to highlight a HTML form element. It sets the element as an active element in the current document. In current documentation, focus can be applied to only one single element. The focus can be applied either to a text, a button, etc.
To set focus to an HTML form element, the focus() method of JavaScript can be used. To do so, call this method on an object of the element that is to be focused, as shown in the example. Example 1: The focus() method is set to the input tag when user clicks on Focus button.
Try using a timer:
const id = "mobileno";
const element = document.getElementById(id);
if (element.value.length >= 10) {
alert("Mobile Number Should be in 10 digits only");
element.value = "";
window.setTimeout(() => element.focus(), 0);
return false;
}
A timer with a count of 0 will run when the thread becomes idle. If that doesn't help, try the code (with the timer) in the onblur
event instead.
2 things to mention if focus()
not working:
This way works in both Firefox and Chrome without any setTimeOut()
.
window.setTimeout(function () {
document.getElementById('mobileno').focus();
}, 0);
This worked for me also. Firefox would set the value of my element, but not give focus to it.
My case was a bit different. I was trying to focus()
an input from within a browser developer console. Turns out it was interfering with the input somehow, and once I minimized the console everything worked as expected. I understand this isn't a programmatical solution, but in case someone found this on a search engine jist like I did, there's a chance this information might help.
Not all elements are focusable but default, there is a tabindex attribute to fix that.
When you assign tabindex= to an element:
It becomes focusable. A user can use the tab key to move from the element with lesser positive tabindex to the next one. The exception is a special value tabindex="0" means that the element will always be last. The tabindex=-1 means that an element becomes focusable, but the tab key will always skip it. Only the focus() method will work
One more thing to add to this list to check:
Make sure the element you are trying to focus is not itself nor is contained in an element with "display: none" at the time you are trying to focus it.
For getting back focus to retype password text box in javascript:
window.setTimeout(function() { document.forms["reg"]["retypepwd"].focus(); },0);
Here, reg
is the registration form name.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With