Question

I expected that calling .submit() on a <form> with javascript would call the validation functions on each <input/>, just like clicking a submit button.

Am I doing something wrong? Is this behavior by design?

<form name="nameForm" action="#" method="post"
      onsubmit="this.name.value = this.name.value + ' (' + location.hostname + ')'">
  <input type="text" name="name"
         placeholder="Your name" required="required" value="" />
  <input type="submit" name="commit" value="Submit" />
</form>
<p>This form has a <code>required</code> field.</p>
<p>
  But <a href="javascript:document.nameForm.submit()">this link</a>
  which calls the form's <code>submit()</code> function doesn't fire
  the <code>required</code> handler.
</p>

Ignore the console error on submit. I have a real submit action.

Was it helpful?

Solution

A workaround is to call document.nameForm.commit.click() from the link, but I still don't understand why the submit action is different.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top