Javascript Form How to - Set focus to Text Field and select all








Question

We would like to know how to set focus to Text Field and select all.

Answer


<!-- ww w  .  j a  va2 s.  c  o m-->
<html>
<head>
<script language="JavaScript">
function checkField(formName)  {
  if (formName.f1.value != "Joe") {
     document.forms[0].f1.focus();
     document.forms[0].f1.select();
  }
}
</script>
</head>
<body>
<form>
    Field1 <input name="f1" onBlur="checkField(this.form)"><br>
    Field2 <input name="f2">
</form>
</body>
</html>

The code above is rendered as follows: