Javascript Form How to - Set focus to input text box








Question

We would like to know how to set focus to input text box.

Answer


<!--  w w  w. j ava2s  .c  o  m-->
<html>
<head>
    <script language="JavaScript">
    function setFocus(num){
      if(num == 1){
        document.myForm.myText1.focus();
      }else if(num == 2){
        document.myForm.myText2.focus();
      }
    }
    </script>
    </head>
    <body>
    <P>
    <form name="myForm">
      <input type=TEXT value="Textbox 1" name="myText1">
      <input type=BUTTON value="Click to Set Cursor" name="myButton1"
             onClick="setFocus(1)">
      <br>
      <input type=TEXT value="Textbox 2" name="myText2">
      <input type=BUTTON value="Click to Set Cursor" name="myButton2"
             onClick="setFocus(2)">
    </form>
</body>
</html>

The code above is rendered as follows: