So many times I’ve built software with a single form, and plenty of AJAX buttons perform other key functions.  This can be done by adding buttons which perform a task different to the main form, and posting using AJAX to perform the data changes.

It works well.  But it does require a bit of extra work to advise the user that yes, they did actually click on the button and yes, the website is actually working.  Disabling the button, showing an in-progress indicator – there are many choices here.

The number of times I’ve thought – wouldn’t it be great if we could just setup a nested form and perform a nice easy submit that does the job.

Well – now you can.  Thanks to the wonder of HTML5.  And it’s so much easier than you’d think.

Let’s say we’ve got this setup:

<form method="post" action="/action/save">
<input id="id" name="id" value="someid" />
<input type="submit" value="Save" />
<input type="submit" value="Delete" />
 </form>

One form – a save button and a delete button.  The setup above causes some problems, because two submit buttons means both will submit the absolute-parent form (/action/save).  We can add further parameters in on the button to see which was called, but really – why?

Especially when you can do this using HTML5:

<form method="post" action="/action/save" id="save-form">
<input id="id" name="id" value="someid" />
<input type="submit" value="Save" form="save-form" />
<input type="submit" value="Delete"  form="delete-form" />
</form>
 <form method="post" action="/action/delete" id="delete-form">
<input id="id" name="id" value="someid" />
</form>

So easy – add a “form” attribute to the submit buttons in the parent form.  Then – outside the parent form, setup a small form with just the controls required to post to the action.  Wire up the “form” attribute to the ID of the relevant form, and bingo – you’ve now got multiple submit buttons posting correctly to the relevant URLs.

Where this does fall apart is when there are PLENTY of data shared between the relevant forms.  It will still work but will add a considerable amount of code.  But for solutions where standard browser “activity” is all that is needed to display to the user that an action is being performed – it’s perfect.

Credit to Shovanik for this solution on Stack Overflow