RE: Set Focus In Input Field With PHP (Original was closed with no solution)

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)

Hi SucceedOnlineUs welcome to the forum

Yes, there is, now that browser support for HTML5 features has improved.

One thing should be noted however

Only one form item in a document can have the autofocus attribute, which is a Boolean.

1 Like

To validate, yes, you are right. I guess I should have noted that in my post. I edited to provide a solution to that issue as well :slight_smile: Thanks!

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.