0

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.

benomatis
  • 5,536
  • 7
  • 36
  • 59
Willy
  • 9,848
  • 22
  • 141
  • 284

1 Answers1

2
//echo "var elem = document.getElementById($id);";
echo "var elem = document.getElementById('".$id."');";

This is probably your problem. You are passing $id without quotes.

Hobbes
  • 781
  • 10
  • 29
  • 1
    you don't necessarily need `".` and `."` as double-quotes are used, but you definitely need the single quotes, otherwise it would be understood by js as a variable... – benomatis Oct 26 '14 at 18:58
  • He can also keep the syntax that variables are parsed in the parenthesis. Just add single quotes around $id – ChrJantz Oct 26 '14 at 18:58
  • Yea I'm just OCD about vars in double quotes =] – Hobbes Oct 26 '14 at 19:03
  • @Hobbes Perfect! A lot of thanks! Your solution works like a charm! Passing incorrect identifier format to getElementById was the problem. – Willy Oct 26 '14 at 19:05