How can I remove empty fields from my form in the querystring?

With JQuery:

$('#form').submit(function (e) {
  e.preventDefault();

  var query = $(this).serializeArray().filter(function (i) {
    return i.value;
  });

   window.location.href = $(this).attr('action') + (query ? '?' + $.param(query) : '');
});

Explanations:

  • .submit() hooks onto the form's submit event
  • e.preventDefault() prevents the form from submitting
  • .serializeArray() gives us an array representation of the query string that was going to be sent.
  • .filter() removes falsy (including empty) values in that array.
  • $.param(query) creates a serialized and URL-compliant representation of our updated array
  • setting a value to window.location.href sends the request

See also this solution.


I love the idea given by RaphDG

But I modified the code a little. I just use the disabled property rather removing the field. Here is the changed code:

<form method="get" id="form1">
    <input type="text" name="aaa" id="aaa" /> 
    <input type="text" name="bbb" id="bbb" /> 
    <input type="submit" value="Go" />
</form>
<script type="text/javascript">
    $(document).ready(function() {
        $("#form1").submit(function() {
            if($("#bbb").val()=="") {
                    $("#bbb").prop('disabled', true);
            }
        });
     });
</script>

Thanks once again for the idea RaphDG (y)


The current solutions depend on the client running Javascript/jQuery - which cannot be guaranteed. Another option is to use a rewrite rule. On an Apache server, I've used the following in order to strip out empty $_GET values from form submissions;

RewriteCond %{REQUEST_URI} \/formpage\/?
RewriteCond %{QUERY_STRING} ^(.*)(&|\?)[a-z-_]+=(?=&|$)(.*)$ [NC]
RewriteRule .* \/formpage?%1%2 [R,L,NE]

... which would turn this ..;

http://www.yoursite.com/formpage?search=staff&year=&firstname=&surname=smith&area=

... into this;

http://www.yoursite.com/formpage?search=staff&surname=smith

A quick explanation:

  1. RewriteCond %{REQUEST_URI} \/formpage\/? is a means to limit the scope of your regular expression to a particular sub-page of your site's address (for example, http://www.yoursite.com/formpage). It's not strictly required, but you may wish to apply the expression only to the page on which the form appears. This is one way of accomplishing this.

  2. RewriteCond %{QUERY_STRING} ^(.*)(&|\?)[a-z-_]+=(?=&|$)(.*)$ [NC] is a second condition, which then matches against the query string (i.e. anything that appears from (or including) the question mark, such as ?firstname=sam$surname=smith). Let's break it down;

    • ^(.*) - The ^ symbol signifies that this is the START of the query string, and the period . is saying ANY character. The asterisk * is a modifier against the period wildcard, saying that any number of them should be included in the scope.
    • (&|\?)[a-z-_]+=(?=&|$) - This is the most interesting bit (if you like this kind of thing ...). This finds your empty query string. Between the first parenthesis, we're stating that the string begins with an ampersand OR a literal question mark (backslash makes the following character literal, in this case - otherwise the question mark has a different meaning). Between the square brackets, we're saying match any character from a-z, OR hyphen - OR underscore _, and immediately after that the plus symbol + is stating that we should match any of those preceding characters 1 or more times. The equals sign = is just what it looks like (the equals between your query string name and its value). Finally, between the next parenthesis, we have a lookahead clause ?=that states that the next character MUST BE an ampersand OR the very end of the line, as indicated by the dollar sign $. The intention here is that your query string will only be considered a match if it's followed by the start of another query string or the end of the line without including a value.
    • The final bits (.*)$ [NC] are just matching against any and all content that follows an empty query string, and the [NC] clause means that this is cASe iNsENsiTIve.
  3. RewriteRule .* \/formpage?%1%2 [R,L,NE] is where we tell mod_rewrite what to do with our matched content. Essentially rewriting the URL to your pagename followed the whole query string except the matched empty strings. Because this will loop over your URL until it ceases to find a match, it does not matter if you have a single empty value or 50. It should spot them all and leave only parameters that were submitted with values. The [NE] clause on the rewrite rule means that characters will not be URL encoded - which may or may not be useful to you if you are expecting special characters (but you obviously need to sanitize your $_GET data when you're processing it, which you should be doing anyway).

Again - this is obviously an Apache solution using mod_rewrite. If you are running on another operating system (such as a Windows server), this will need to be adjusted accordingly.

Hope that's of some use to someone.


You could use jQuery's submit function to validate/alter your form:

<form method="get" id="form1">
    <input type="text" name="aaa" id="aaa" /> 
    <input type="text" name="bbb" id="bbb" /> 
    <input type="submit" value="Go" />
</form>
<script type="text/javascript">
    $(document).ready(function() {
        $("#form1").submit(function() {
            if($("#bbb").val()=="") {
                    $("#bbb").remove();
            }
        });
     });
</script>