Greg's Blog

helping me remember what I figure out

Javascript: Setting the Form Focus

| Comments

One of my pet grievances is hitting a page with a search or username and password field, where I need to click on the field so that I can start entering text. I will briefly explain in the following how you can set the focus on a form field, so that a cursor appears there, once the page has loaded.

Suppose you have form named frm_search, i.e. your form statement would look something like this:

<form action=”search_results.html” method=”post” enctype=”multipart/form-data” name=”frm_search”>

And the field name you wanted to set the focus to was called txt_search, you would need to specify in the <body> of your page the following onLoad function:

onLoad=”document.frm_search.txt_search.focus();”

Et voila, when the page loads, you should find the cursor blinking in that form field. Not very complicated and so much more user friendly. So to recap here is the entire code:

<html>
<head>
<title>Focus</title>
</head>
<body onLoad=”document.frm_search.txt_search.focus();”>
<form action=”search_results.html” method=”post” enctype=”multipart/form-data” name=”frm_search”>
<input type=”Text” width=”100” name=”txt_search”>   <input type=”Submit” name=”btn_search” value=”Submit”>
</form>
</body>
</html>