A nerd pretending to be a software engineer.

TIL: formmethod and formaction

Written on

TIL: HTML input elements allows you to specify formaction and formmethod attribute that let you override action and method attribute of the element’s parent form.

In a web application that I’m working on, there’s a product listing page that allows the user to specify some search criteria and filter the products listing to only display the items that matches the search criteria. This product listing is rendered as a HTML table, and users can also export the entire product listing and download them as CSV.

There are several ways I can implement that page. I can implement the search form will render the filtered table, and along with the filtered table, render the another form that submits the current search parameters in hidden fields to the CSV export endpoint. This means the user must first preview the list in HTML before they can export them.

Another option is to pull Javascript thats takes the input values of the first form and use that to generate the second form and submit it upon button click. This would mean I had to put Javascript in an otherwise server-rendered page. Neither approach is really satisfactory.

With the formaction, I can simply add a second submit button to the form and specify the second endpoint there. Not only I can avoid unnecessarily making the page depend on Javascript, I also had to write much less code. It’s a nifty little feature of HTML5 that helped me delete many lines of code.


While titled “TIL”, I actually learnt about this a while ago while listening to my podcast backlog, and I’m really glad the hosts talked about the feature since it was really applicable in solving an issue I’ve been having. And since I recently decided to start writing more again, but had been having trouble getting over the block, I thought I would use this little topic to build up the momentum to write more.

comments powered by Disqus