I would like to set the focus and then select the contents (in case text input type) for several object types in my page.
In my form I have these type of objects:
- text
- checkbox
- radio
and also Select object (this is a drop-down list).
I have a form which contains these objects and also a submit button. On submit I do a validation on the fields one by one. If I find an error I would like to set the focus on that object so I do:
In below code $id
is that identifier of the object, that is, id
attribute. Code snippet of my PHP page:
<?php
(...)
function SetFocus($id)
{
echo "Setting focus to: " . $id . "#";
echo "<script type='text/javascript'>";
echo "var elem = document.getElementById($id);";
echo "elem.focus();";
echo "elem.select();";
echo "</script>";
}
(...)
?>
<form ........>
<input name="personName" type="text" id="personName">
(...)
<?php
(...)
$errMsg = "";
$id = "";
if (!Validate($errMsg, $id))
{
ShowError($errMsg);
SetFocus($id);
}
(...)
?>
(...)
</form>
Validate function is placed in an include PHP file, and it returns by reference the custom error message according to the element being checked and its corresponding identifier (identifier corresponds to the id
attribute of the element). If validation is not ok then I call ShowError
to show the message within the page (not through a popup windows) and then I set the focus in the element containing the error by calling SetFocus
function.
My problem is that SetFocus
function is not working. Element that is in error is not handling the focus and neither selected.