Milk Milk - 3 months ago 20
HTML Question

Submit a form without query string

I'm on a page like

http://example.com?query=value
that has a form
<form id="formId" method="POST">
.

What's the best way to submit the form to
http://example.com
without the query string?

I'm currently trying:

$('#formId').submit(function(e){
e.preventDefault();
var url = window.location.href;
if (url.indexOf("?") != -1){
$('#formId').attr('action', url.split("?")[0]);
}
$('#formId').submit();
});


but it doesn't seem to be working.

I prefer a javascript/jQuery solution as this pattern is common through the site

Answer

Instead of attempting to change the action on submit, how about just looking for forms without action attributes and setting them appropriately, for example

jQuery(function($) {
    $('form:not([action])').attr('action', location.pathname);
});