Your code as quoted should be working, and does in my tests with a variety of browsers. (I've tried it locally, with a POSTed form, but you can also try it here: http://jsbin.com/ehoro4/1 I've changed the method to GET
so you can see the result in the URL.)
My guess is that you have something else on the page with the name
or id
"hiddenField", other than just the hidden field you've quoted. If you change the name of the field to "fluglehorn" or something else that's (um) unlikely to be elsewhere on your page, it may well work. That's because the namespace used by getElementById
is (sadly) quite crowded.
Alternately, are you sure that genarate
is appearing at global scope? (E.g., it's outside of all other functions.) Because your onsubmit
attribute requires that genarate
be global. So this works:
<form action="#" method="get" onsubmit="genarate('hiddenField')">
<input type="hidden" id="hiddenField" name="hidden" value=""/>
<input type="submit" name="submit"/>
</form>
<script>
function genarate(hiddenField){
var field = document.getElementById(hiddenField);
field.value = "new Value";
}
</script>
but for example this would not:
<form action="#" method="get" onsubmit="genarate('hiddenField')">
<input type="hidden" id="hiddenField" name="hidden" value=""/>
<input type="submit" name="submit"/>
</form>
<script>
(function() { // Begin scoping function to avoid global symbols (not uncommon)
function genarate(hiddenField){
var field = document.getElementById(hiddenField);
field.value = "new Value";
}
})();
</script>
Also recommend using a debugger (there's no excuse for not using client-side debuggers here in 2011) to set a breakpoint on the genarate
function and walk through, to see what's going wrong.
field.setAttribute('value', "new Value");
instead offield.value
? (just guessing here ;)) – Felix Klingfield.value = "new Value";
tofield.setAttribute('value', "new Value");
and changing nothing else solved the problem? I find that very hard to believe, setting field values via thevalue
property is bog standard and has been since 1995 or so. I've tried your code with IE6, IE9, Firefox 3.6, Chrome 10, Opera 11, and Safari 5. It works withfield.value = "new Value";
, full stop. You must have changed something else at the same time. – T.J. Crowder