View Full Version : The onload function is not setting value.

05-12-2009, 09:47 PM
I am having problems with setting a value with onload. Here is an example of the code.

<form method="get" class="searchform" action=theAction" onload="if('' == '') {document.getElementById('searchinput').value='Type Search Query';} else {document.getElementById('searchinput').value='june';}">
<input class="searchinput" name="s" type="text">
<input class="searchbutton" value="Go" type="submit"></form>

I know you guys might be thinking that the if condition is hard coded, and the if will never change. In the real code, php changes the first value of the if's condition.

I think the above code should always set the value 'Type Search Query', in the box. However, it does not set any value.

Can someone please explain what is going on? Also, is there another, btter way to do something like this a different way?


Philip M
05-12-2009, 10:00 PM
form...onload is not valid javascript. And as the input field doesn't exist until the page is loaded you need to place the code to set the value of the field into a function and call the function from the global event handler like this:

Try this:-

<script type = "text/javascript">
function init() {
if ('' == '') { // whatever condition applies
document.getElementById('sinput').value = 'Type Search Query';
else {
window.onload = init;

<input type = "text" class="searchinput" name = "sinput" id = "sinput"

Quizmaster: Who sang the theme tune to the James Bond film "Goldfinger"?
Contestant: Shirley Temple.

05-14-2009, 07:24 AM
Thanks. I will consider that. Another person suggested, just making the if statement in the php code, and handling it that way. I htink I might go with that. Thanks, I will use this as a back up plan I guess.