I want to have a form on the main section of my webpage with buttons along the bottom of this section to submit it.
I also want to have a side bar with links to other pages, but make it so that whenever a link is clicked it acts as a button to submit the form too. (ie in the HTML, the code for these links will be outside of the form tags, but I would like them to still act as buttons for the form)
Is this possible?
Advertisement
Answer
The easiest way to ensure your form is submitted and validated by whatever function you’ve attached is not to call the form’s submit()
method, but to call its submit button’s click()
method instead.
Consider the following form:
<form id="bar" method="post" action="/echo/html/"> <input type="text" id="foo" name="foo"> <input type="submit" value="Submit"> </form>
Right now, clicking submit doesn’t do anything special. But what if you wanted to ensure the text input had a value before sending anything off to the server? You might accomplish that as follows:
function validateBarForm() { var txt = this.querySelector("input[type=text]"); if (txt.value == "") { txt.style.outline = "solid red 2px"; return false; } } document.getElementById("bar").onsubmit = validateBarForm;
Now if you click submit the form won’t be submitted with a blank text input. But what if you submit the form programmatically? Let’s add a link first…
<a href="#" id="submit-bar">submit form</a>
Note that this link is outside of the form tag. We can trivially attach a submission function:
function submitBarForm() { document.getElementById("bar").submit(); } document.getElementById("submit-bar").onclick = submitBarForm;
We click “submit form” and… Whoops! The validation function is not performed! There are a few ways to skirt this issue, but my favourite is to simply have JavaScript simulate a click to the submit button. I find this holds up to changes a lot better than hardcoding a call to the validation function.
function submitBarForm() { document.querySelector("#bar input[type=submit]").click(); }
Now when you click the link, the form is validated, and if everything checks out it’s submitted too. But don’t take my word for it–head on over to jsfiddle.net and see for yourself.