Set focus in input field with php

hi all

To be on safer side i m adding server side validation to my form.

So i would like to know if there is something similar to below “focus” code in php



Yes - server side validation is mandatory, client side is nice to have.

If you are talking about the form returned to the user, all that PHP can do is send back a stream of html/js which can contain your .focus() instruction so that the required form element lights up or whatever.

You are best off adding a html message as well in case JS is turned off/unavailable.


echo "<p>Please add your name</p>";
echo "<input type=text name=fname id=fname '/>";


That is a simple example of a way of doing it for illustrative purposes, I’m sure you can improve upon it and integrate it.

hi cups

thanks for the reply.

i will surely be adding/displaying error messages near the input fields.

i thought it would be better if i could set focus also on the input field through php.

but thats not be possible with php i think ?


Well, you will have to output some js into the stream of html which includes something like:


hi cups

i need a solution that will work even if javascript is disabled.

totally php without javascript


Sadly there is no solution for this. What you’re trying to do is dynamically modify the webpage in real-time (client side) - This is what JavaScript was made for. I believe it’s a rediculously small number (something like 2 or 3%) of users actually browse with JavaScript disabled so there is no need for it either.

There is probably a high number of that small number who are visually handicapped and use a screen reader which disables JS.

So, sticking focus on a named form element is a “nice to have”, and if you are designing for non-JS enabled readers is not possible so I suggest you accept that think up other ways of bringing it to the attention of the user.