views:

27

answers:

1

Hi,

I'm working on a simple script to pass the value " ...php?answer=1" if java is enabled. I've got this far ...

<script language="text/javascript">
document.form.answer.value=1;
</script>
</head>
<body>
<form name="form" action="enabled_catch.php" method="get">
<input type="hidden" name="answer">
<input type="submit" value="click me">
</form>

... but the script does not appear to ba assigning answer.value="1" - I'm not sure why. Can you help

+8  A: 

This happens because at the moment you are assigning this value using javascript (do not confuse with Java) the DOM is not loaded yet and the form doesn't exist. Try this instead:

<script type="text/javascript">
window.onload = function() {
    document.form.answer.value = '1';
};
</script>

or better assign an id to your input and use this id:

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

or even better use a javascript framework such jQuery to manipulate the DOM to ensure cross browser compatibility:

<script type="text/javascript">
$(function() {
    $(':hidden[name=answer]').val('1');
});
</script>
Darin Dimitrov
The other alternative is to move the javascript block to the end of the document, somewhere after the `<input>` tag.
Marc B
@Marc B, yes, good point.
Darin Dimitrov
all the above work great - UNTIL I add <body onload="document.form.submit();"> (because I want this process to happen automatically), then the value fails to return
giles
Don't add `onclick` attribute to the body tag or it might conflict with the `window.onload`. Use one or the other.
Darin Dimitrov