Easiest way to have 2 submit button in one html form

June 12, 2009 on 4:41 pm | In DHTML, JavaScript | No Comments

Here is the easiest way to have two (or more) submit buttons in one html form and to make them “do” something else. It is very helpful if you are planning to implement a toolbar like behavior. Example is from ASP.NET MVC but it does not matter. Since it uses JavaScript to dynamically change the action attribute of a form tag, it can be used everywhere. Here it is:

    <h2><%= Html.Encode(ViewData["Message"]) %></h2>

    <script language="javascript" type="text/javascript">
        function ChangeFormAction(sender, url) {
            sender.form.action = url;
        }
    </script>

    <form method="post">
        <input id="text" name="text" type="text" value="Hello from Action" />
        <br />
        <input type="submit" value="Go to action 1"
            onclick="ChangeFormAction(this, '/Home/Action1')" />
        <input type="submit" value="Go to action 2"
            onclick="ChangeFormAction(this, '/Home/Action2')" />
    </form>

And the actions that responds to this form are here:

public class HomeController : Controller
{
    public ActionResult Action1(string text)
    {
        ViewData["Message"] = text + "1";

        return View("Index");
    }

    public ActionResult Action2(string text)
    {
        ViewData["Message"] = text + "2";

        return View("Index");
    }
}
Nice!

Powered by WordPress with Pool theme design by Borja Fernandez.
Text © Marcin Kawalerowicz. Hosting CODEFUSION.