Vincent A Saulys' Blog
Delete Buttons in HTML
Tags: javascript
April 20, 2021

Working on a project lately, I've noticed that HTML and Javascript don't behave like you'd always think.

For instance, if you write a form like below:

<form action="">
  <input name="" type="text" value=""/>
  <input name="" type="text" value=""/>

  <button type="submit">Submit</button>
  <button>Delete</button>
</form>

Both buttons will actually submit.

HTML5 supports three types for button:

Annoyingly, HTML does not support PUT or DELETE methods for its native forms. If you want to have a button do something else, like delete, you can follow this all html pattern to do so.

<form action="">
  <input name="" type="text" value=""/>
  <input name="" type="text" value=""/>
  <input id="_delete" name="" type="hidden" value=""/>

  <button type="submit">Submit</button>
  <button onclick="document.querySelector('#_delete').value = 'true'">Delete</button>
</form>

The idea is to use a hidden field to hide extra information in your form that your users never see. Upon clicking the delete button, the form will attach a value to this hidden field. This will appear in the request body of your backend view (e.g. req.body if you're in expressJS).

You can then check this flag. If it doesn't exist, then its a normal submit. If it does, then its a delete request and you use a flag to check.

This extends easily to something like ajax if you want to submit a proper DELETE request. A POST request would go through if used like this.

Share on...