Javascript focus on input box on load
14,524
Solution 1
Double quotes cannot include double quotes,not only in javascript,any other language is the same.
<body onload="document.getElementById('search').focus()">
Solution 2
I'f you're using jquery:
$(function() {
$("#search").focus();
});
or prototype:
Event.observe(window, 'load', function() {
$("search").focus();
});
or plain javascript:
window.onload = function() {
document.getElementById("search").focus();
};
It's "Better" for readability than an inline event...
Author by
Jabey
Updated on June 19, 2022Comments
-
Jabey almost 2 years
No matter what I do, this page doesn't work at all. I want it to focus on the input box on load.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <title>Home Screen</title> <style type="text/css"> input {border:0px;} input:focus {outline:none;} </style> </head> <body onload="document.getElementById("search").focus()"> <input id="search" /> </body> </html>
I know I'm breaking a bunch of rules with this code, so you don't need to say anything about that.
EDIT:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <title>Home Screen</title> <style type="text/css"> input {border:0px;} input:focus {outline:none;} </style> </head> <body onload="document.getElementById('search').focus()"> <input id="search" onblur="setTimeout(document.getElementById('search').focus(),10)" /> </body> </html>
EDIT 2:
<script type="text/javascript"> function refocus() { setTimeout(document.getElementById("search").focus(),10); } </script> <input id="search" onblur="refocus()" />