Search code examples
javascripthtmlformsonclicksubmit

Change value of input and submit form in JavaScript


I'm currently working on a basic form. When you hit the submit button, it should 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 code. It changes "myinput"'s value to 1, but it does not submit the form.

function DoSubmit(){
  document.myform.myinput.value = '1';
  document.getElementById("myform").submit();
}

Solution

  • You could do something like this instead:

    <form name="myform" action="action.php" onsubmit="DoSubmit();">
        <input type="hidden" name="myinput" value="0" />
        <input type="text" name="message" value="" />
        <input type="submit" name="submit" />
    </form>
    

    And then modify your DoSubmit function to just return true, indicating that "it's OK, now you can submit the form" to the browser:

    function DoSubmit(){
      document.myform.myinput.value = '1';
      return true;
    }
    

    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.