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:

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.

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.

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