Is there a simple way to set the focus (input cursor) of a web page on the first input element (textbox, dropdownlist, ...) on loading the
Putting this code at the end of your body
tag will focus the first visible, non-hidden enabled element on the screen automatically. It will handle most cases I can come up with on short notice.
<script>
(function(){
var forms = document.forms || [];
for(var i = 0; i < forms.length; i++){
for(var j = 0; j < forms[i].length; j++){
if(!forms[i][j].readonly != undefined && forms[i][j].type != "hidden" && forms[i][j].disabled != true && forms[i][j].style.display != 'none'){
forms[i][j].focus();
return;
}
}
}
})();
</script>
With AngularJS
:
angular.element('#Element')[0].focus();
For those who use JSF2.2+ and cannot pass autofocus as an attribute without value to it, use this:
p:autofocus="true"
And add it to the namespace p (Also often used pt. Whatever you like).
<html ... xmlns:p="http://java.sun.com/jsf/passthrough">
without jquery, e.g. with regular javascript:
document.querySelector('form input:not([type=hidden])').focus()
works on Safari but not Chrome 75 (april 2019)
You also need to skip any hidden inputs.
for (var i = 0; document.forms[0].elements[i].type == 'hidden'; i++);
document.forms[0].elements[i].focus();