Original Here: Set focus in input field with php
The user asked how to Set Focus In Input Field With PHP. The Thread was closed with no solution. There actually is a solution.
HTML syntax provides “autofocus” The solution would be as simple as this…
<!-- Include form handler script -->
<form action="<?php $_SERVER['PHP_SELF']; ?>">
<input type="text" name="name" value="Your Name" <?php echo $name_autofocus; ?> />
<input type="text" name="email" value="Email Address" <?php echo $email_autofocus; ?> />
<input type="submit" value="Submit">
</form>
Now, in the form handler script we validate fields and set the empty “autofocus” variables to “autofocus” where applicable.
<?php
$name_autofocus = ''; //Set initial value to empty
$email_autofocus = ''; //Set initial value to empty
$af_array = array();
if( ( isset( $_REQUEST['name'] ) ) && ( strlen( $_REQUEST['name'] ) < 2 ) ){
/* Set An Error Message/Variable Here */
$af_array['name']='autofocus';
}
if( ( isset( $_REQUEST['email'] ) ) && ( !filter_var( $_REQUEST['email'], FILTER_VALIDATE_EMAIL ) ) ){
/* Set An Error Message/Variable Here */
$af_array['email']='autofocus';
}
/*
* Loop through the array to find the first occurrence of "autofocus"
* set that field to "autofocus"
* exit loop always keeping focus on the first erroneous field
*/
foreach ( $af_array as $key => $value ) {
if( preg_match( '/autofocus/', $value ) ){
$key = $key.'_autofocus';
$$key = $value;
break; // Stop and focus on first invalid field
}
}
?>
There you have it! Please do not forget to sanitize your form inputs! (omitted here for simplicity)