Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change form action based on submit button

I have many forms like the following on the page. Now I want change the form action based on which submit button the user clicked (and of course submit the form)

<form action="/shop/products.php" data-ajax="false" method="post">
    <div data-role="fieldcontain">

        <input name="submit" class="obutn" type="submit" value="Order" />
        <input name="submit" class="oEbutn" type="submit" value="Extras" />

    </div>
</form>

I tried with

$(".obtn").click(function() {
    $(this).parent().parent().attr("action", "/shop/products.php");     
});
$(".oEbtn").click(function() {
    $(this).parent().parent().attr("action", "/shop/extras.php");       
});

but the form is always submited to products.php. Can you tell me what's wrong?

like image 808
Bad Pussycat Avatar asked Jul 15 '13 18:07

Bad Pussycat


People also ask

How do you link a button to a form in HTML?

The plain HTML way is to put it in a <form> wherein you specify the desired target URL in the action attribute. If necessary, set CSS display: inline; on the form to keep it in the flow with the surrounding text. Instead of <input type="submit"> in above example, you can also use <button type="submit"> .

Can a form have multiple actions?

Let's learn the steps of performing multiple actions with multiple buttons in a single HTML form: Create a form with method 'post' and set the value of the action attribute to a default URL where you want to send the form data. Create the input fields inside the as per your concern. Create a button with type submit.


1 Answers

Instead of setting the action attribute on the form itself, consider setting formaction attribute on each individual input element.

Docs: http://www.w3.org/TR/html-markup/input.submit.html#input.submit.attrs.formaction

<form data-ajax="false" method="post">
    <div data-role="fieldcontain">
        <input formaction="/shop/products.php" 
               name="submit" class="obutn" type="submit" value="Order" />
        <input formaction="/shop/extras.php" 
               name="submit" class="oEbutn" type="submit" value="Extras" />
    </div>
</form>
like image 98
xorcus Avatar answered Oct 05 '22 08:10

xorcus