HTML5 button.formaction Attribute Not Working Outside of <form>

11,463

In general form elements are used to send data to a server. It wraps around the elements which specifies the data, input or button elements, for instance. If you add a name and a value attribute to your button elements, you will send this name-value-pair to your server.

If you don’t need to send any (additional) data to your server, just use link elements and style them like buttons using CSS, if you want to:

<a href="a.jsp" class="btn">a</a>
<a href="b.jsp" class="btn">b</a>
<a href="c.jsp" class="btn">c</a>

The formaction attribute

With the formaction attribute you can specify multiple submit URLs for one form. Because the action attribute is no longer required for the form element you could define the submit URL(s) just in the formaction of a submit button. When the form is submitted, the browser first checks for a formaction attribute; if that isn’t present, it proceeds to look for an action attribute on the form element. So the form action is something like a fallback or default, it is not required:

<form method="post">    
    <input type="text" name="my-data" value="my data"/>

    <button type="submit" formaction="a.jsp">a</button>
    <button type="submit" formaction="b.jsp">b</button>
    <button type="submit" formaction="c.jsp">c</button>        
</form>

If you use the form attribute on the button to reference the associated form (id value) you could even place the button outside of the form element:

<form method="post" id="myForm">
    <input type="text" name="my-data" value="my data"/>
</form>

<button type="submit" formaction="a.jsp" form="myForm">a</button>
<button type="submit" formaction="b.jsp" form="myForm">b</button>
<button type="submit" formaction="c.jsp" form="myForm">c</button>
Share:
11,463
Admin
Author by

Admin

Updated on July 24, 2022

Comments

  • Admin
    Admin almost 2 years

    Why does the button.formaction attribute not work outside of a <form>?

    This fails:

    <button type="submit" formaction="a.jsp">a<button>
    <button type="submit" formaction="b.jsp">b<button>
    <button type="submit" formaction="c.jsp">c<button>
    

    However, this works for me:

    <form action="foo.jsp" method="post">
        <button type="submit" formaction="a.jsp">a<button>
        <button type="submit" formaction="b.jsp">b<button>
        <button type="submit" formaction="c.jsp">c<button>
    </form>
    

    But in my application it does not make sense for me to use a form since I never want to access foo.jsp and I do not have a default. Is there some way to make formaction work without using a dummy value or defaulting the form to a.jsp?