title: Set focus on HTML form element using JavaScript
body: <p>I have a form element and I'm doing a small validation. I want my text box to be focused if it is invalid.</p>
  
  <p>This is my HTML</p>
  
  <pre><code>&lt;form id="frm" name="form1" onsubmit="validate()"&gt;
      Name: &lt;input type="text" id="t1" name="txtBox"&gt;
      &lt;input type="submit" value="submit"&gt;
  &lt;/form&gt;
  </code></pre>
  
  <p>This is my script:
  I want to focus the form element from else part</p>
  
  <pre><code>&lt;script&gt;
      function validate(){
          var inp = frm.getElementsByTagName("input");
          var arr=[];
          var i;
          for(i=0;i&lt;inp.length;i++){
              arr[i]=inp[i].getAttribute("id");
              //document.write(arr[i]);
          }
          //alert(inp[0].value);
          if(form.validateText(inp[0],arr[0])){
              return true;
          }
      }
  
      var form = {
          validateText : function(f,i){
              var input = document.getElementById(i);
              var reg = /^[a-zA-Z]$/;
              //var 
              var x = f;
              if(x.value.match(reg)){
                  return true;
              }
              else{
                  alert("invalid text");
                  input.value.focus();
              }
          }
      };
  &lt;/script&gt;
  </code></pre>