I'm currently working on a basic form. What I want to do with this form is that when you hit submit/button to first change the value of a field and then submit the form as usual. It all looks a bit like this:
<form name="myform" id="myform" action="action.php">
<input type="hidden" name="myinput" value="0" />
<input type="text" name="message" value="" />
<input type="submit" name="submit" onclick="DoSubmit()" />
</form>
And this is how far I've come with the JavaScript. It changes "myinput"'s value to 1 but does not submit the form. I'm really a JavaScript noobie so forgive me if this is just a too simple question but I'm just not getting the hang of it really.
function DoSubmit(){
document.myform.myinput.value = '1';
document.getElementById("myform").submit();
}
No. When your input type is submit, you should have an
onsubmit
event declared in the markup and then do the changes you want. Meaning, have anonsubmit
defined in your form tag.Otherwise change the input type to a button and then define an
onclick
event for that button.You could do something like this instead:
And then modify your DoSubmit function to just return true, indicating that "it's OK, now you can submit the form" to the browser:
EDIT: I'd also be wary of using onclick events on a submit button; the order of events isn't immediately obvious, and your callback won't get called if the user submits by, for example, hitting return in a textbox.
You're trying to access an element based on the
name
attribute which works for postbacks to server but javascript responds to theid
attribute. Add anid
with the same value asname
and all should work fine.here is simple code , you must set an id for you input here call it 'myInput' :
My problem turned out to be that I was assigning as
document.getElementById("myinput").Value = '1';
Notice the capital V in Value? Once I change it to small case ie; value, the data started posting. Odd as it was not giving any Javascript errors as well
This wont work as your form tag has no id.
Change it like this and it should work: