The formtarget attribute

You may already know the target attribute from links, the same attribute can also be used on <form> elements. Which brings us to the formtarget attribute, this can be used on submit buttons (<button>, <input type="submit"> and <input type="image">) and let you override the target attribute of the parent form.

Possible values #

There are five different values we can use:

_self: The default one, will load response in current window (browsing context)

_blank: Will load response in new windows/tab

_parent: Will load response in parent frame (e.g. submit a form in an iframe (b.html) which is nested in another iframe (a.html) which appear on page (hello.html), the response will load in the outer iframe (a.html) – if there is no parent frame it will behave like _self

_top: Will load response in the main window – again this is for frames. Taking the example from above a response from a form in b.html will load in hello.html

Name of iframe: Will load the response in the iframe with the matching name.

Handle form in a referenced iframe #

Let's look at an example how referencing an iframe can be used, as this is the most fun one of all the possibilities and this page is not called boring with forms. I found this via CSS-Tricks and here is how this looks in HTML:

<form method="post" action="/test">
<label for="message">Message</label>
<input type="text" id="message" name="message">

<input type="submit" formtarget="test">

<iframe name="test" src="/test"></iframe>

When a user submits the form, the response will be handled in the iframe, as we used formtarget="test" and the iframe has name="test" – which connects them.

I made a demo of this, if you add a message and submit the form it will be posted to the iframe and the iframe will show the message you inserted



As always, I hoped you learned something new about forms. Have fun with forms!

Resources #