SitePoint Sponsor

User Tag List

Results 1 to 2 of 2
  1. #1
    SitePoint Zealot
    Join Date
    Aug 2009
    Posts
    104
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    javascript function to set the focus to a selected field

    Hello

    I am trying to write a javascript function so when the web page loads, I can decide for each particular page, what field to set the focus on.
    and put this function call in to the body onload event.

    For example, on one page, I would like to set the focus to this field:
    document.Form1.user_id

    I tried this code:

    Code:
    function SetTheFocus(sField)
    {	
    	var sTemp = (eval ("document.Form1" + sField));
    	sField.focus();
    }
    but when I call it in the body tag....

    <body onload="SetTheFocus('user_id');">

    it doesn't work.

    How do I fix this?

    Thanks.

  2. #2
    SitePoint Wizard bronze trophy chris.upjohn's Avatar
    Join Date
    Apr 2010
    Location
    Melbourne, AU
    Posts
    2,189
    Mentioned
    17 Post(s)
    Tagged
    1 Thread(s)
    Your above code is never going to work as your targeting the variable sField which is just a string when in your function your finding and setting the element to your sTemp variable, simply change sField.focus() to sTemp.focus() and it should work fine. However in saying that I wouldn't recommend you use eval as it is considered extremely bad practice to use it when its not absolutely needed, see the below for how you could write the above code in a safe way.

    Code JavaScript:
    function SetTheFocus(sField) {
        if (document.forms['Form1']) {
            var field = document.forms['Form1'].elements[sField] || false;
     
            if (field) {
                field.focus();
            }
        }
    }


Tags for this Thread

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •