Set focus on the first text field of HTML form.

A HTML form is a very good channel that you can offer to your visitors to contact you. An aesthetically appealing form encourages user to fill and submit it. It is equally important to make the form as user friendly as possible. Today I’ll share a small JavaScript function that will set the focus on the first editable text field of your form. So when the web page loads the users don’t have to click on the text field. They can just start typing as soon as the form loads.

Here is the JavaScript code.

function setFocus(){
 var flag=false;
 for(z=0;z<document.forms.length;z++){
  var form = document.forms[z];
  var elements = form.elements;
  for (var i=0;i<elements.length;i++){
    var element = elements[i];
    if(element.type == 'text' &&
      !element.readOnly &&
      !element.disabled){
      element.focus();
	  flag=true;
     break;
    }
  }
  if(flag)break;
 }
}

How to use this script.

Save the script in a text file and name it focus.js.

To use script copy and paste following line into the header section of your form HTML file.

<script type=”text/javascript” src=”focus.js”>

If you saved the focus.js to a separate directory, include the directory with the file name (like src=”js/focus.js”).

Now add

onLoad=”setFocus();”

to the body tag.
Your body tag will become

<body onLoad=”setFocus(‘contactForm’);” >

Now when your page loads the focus will be on the first editable textfield on your form.Click here to see an example.