my HTML code:
<form action="Generator.klx" method="post" onsubmit="genarate('hiddenField')">
<input type="hidden" id="hiddenField" name="hidden" value=""/>
<input type="submit" name="submit"/>
</form>
my JavaScript:
function genarate(hiddenField){
var field = document.getElementById(hiddenField);
field.value = "new Value";
}
But it just didnot work :(. Can anybody tell me where I was wrong?
Thank you
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
GETso you can see the result in the URL.)My guess is that you have something else on the page with the
nameorid“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 bygetElementByIdis (sadly) quite crowded.Alternately, are you sure that
genarateis appearing at global scope? (E.g., it’s outside of all other functions.) Because youronsubmitattribute requires thatgenaratebe global. So this works:but for example this would not:
Also recommend using a debugger (there’s no excuse for not using client-side debuggers here in 2011) to set a breakpoint on the
genaratefunction and walk through, to see what’s going wrong.