Skip to content
Advertisement

HTML button to submit a form elsewhere on the page

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:

JavaScript

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:

JavaScript

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…

JavaScript

Note that this link is outside of the form tag. We can trivially attach a submission function:

JavaScript

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.

JavaScript

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.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement