1

I'm working on the following. It basically passes ?answer=1 if js is enabled. It works until I add the onload argument (as I want this to happen without a user trigger). However adding onload appears to stop (the otherwise working) getElementById argument. Why is this happening?

<script type="text/javascript">
window.onload = function() {
document.getElementById('answer').value = '1';
}
</script>
</head>
<body onload="document.forms[0].submit();">
<form name="form" action="enabled_catch.php" method="get">
<input type="hidden" name="answer">
</form>

thanks

Justin Ethier
  • 122,367
  • 49
  • 219
  • 273
giles
  • 11
  • 1
  • 2
    They're the same thing - in other words, `window.onload` refers to the same thing as the `onload` attribute of the `` tag. – Pointy Aug 28 '10 at 15:36
  • Also, you're using `getElementById()` but your input element has no "id" attribute - that works in IE because IE is broken, but it won't work in proper browsers. – Pointy Aug 28 '10 at 15:36
  • so why does body onload appear to stop window.onload from working? – giles Aug 28 '10 at 15:40
  • Because there are not two different `onload` handlers - you assign the first handler in your ` – Pointy Aug 28 '10 at 16:09
  • this is a duplicate of http://stackoverflow.com/questions/191157/window-onload-vs-body-onload – Mark Hosang Apr 28 '11 at 02:47
  • to answer your question, if you set both body.onload and window.onload one will overwrite the other. like a = b a = c – Mark Hosang Apr 28 '11 at 02:49

1 Answers1

2

Try this instead:

window.onload = function() {
  document.getElementById("answer").value = '1';
  document.forms[0].submit();
}

As I said in my comment, window.onload is the same thing as the "onload" handler for the <body> tag. You can't have one be one function and the other be another function, therefore, because the "other" isn't really another thing - it's the same thing.

Also, your <input> element needs an "id":

<input type='hidden' name='answer' id='answer'>
Pointy
  • 371,531
  • 55
  • 528
  • 584