How to use JavaScript to change the form action
I wanted to use JavaScript to change a form's action, so I could have different submit inputs within the same form linking to different pages.
I also had the added complication of using Apache rewrite to change example.com/page-name
into example.com/index.pl?page=page-name
. I found that changing the form's action caused example.com/index.pl
(with no page parameter) to be rendered, even though the expected URL (example.com/page-name
) was displayed in the address bar.
To get around this, I used JavaScript to insert a hidden field to set the page parameter. I still changed the form's action, just so the address bar displayed the correct URL.
function setAction (element, page)
{
if(checkCondition(page))
{
/* Insert a hidden input into the form to set the page as a parameter.
*/
var input = document.createElement("input");
input.setAttribute("type","hidden");
input.setAttribute("name","page");
input.setAttribute("value",page);
element.form.appendChild(input);
/* Change the form's action. This doesn't chage which page is displayed,
* it just make the URL look right.
*/
element.form.action = '/' + page;
element.form.submit();
}
}
In the form:
<input type="submit" onclick='setAction(this,"my-page")' value="Click Me!" />
Here are my Apache rewrite rules:
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} !-f
RewriteRule ^/(.*)$ %{DOCUMENT_ROOT}/index.pl?page=$1&%{QUERY_STRING}
I'd be interested in any explanation as to why just setting the action didn't work.
If you're using jQuery, it's as simple as this:
$('form').attr('action', 'myNewActionTarget.html');
Try this:
var frm = document.getElementById('search-theme-form') || null;
if(frm) {
frm.action = 'whatever_you_need.ext'
}
function chgAction( action_name )
{
if( action_name=="aaa" ) {
document.search-theme-form.action = "/AAA";
}
else if( action_name=="bbb" ) {
document.search-theme-form.action = "/BBB";
}
else if( action_name=="ccc" ) {
document.search-theme-form.action = "/CCC";
}
}
And your form needs to have name
in this case:
<form action="/" accept-charset="UTF-8" method="post" name="search-theme-form" id="search-theme-form">