Dynamically changing HTML form action using jQuery

In order to test a RESTful service I’m currently working on I’ve created a simple HTML page with a bunch of forms. These forms generate various POST/GET requests to my REST service API methods, so I can manually test the service during a development process. One issue I faced was that the action attribute of HTML form element is static while I need to modify it dynamically based on user’s input (i.e. so I can send a GET requests to a URL like http://www.myrestfulservice.com/item/{itemID} where itemID is entered to the form by a user). JavaScript comes to mind.

So here is how this could easily be done with jQuery:

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <script type="text/javascript" src='http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js'></script>
    <script type="text/javascript">
        $(document).ready(function() {
            $("#getForm :submit").click(function() {
                var item = $(":input#itemId").val();
                $("#getForm").attr("action", "http://www.myrestfulservice.com/" + item);
            });
        });
    </script>
</head>
<body>
    <p>
        Enter item ID get:
        <input type="text" size="50" id="itemId" />
    </p>
    <form id="getForm" method="get" action="">
        <input type="submit" value="Get Item" />
    </form>
</body>
</html>

0 comments: