Sandro Munda
Sandro Munda

Reputation: 41030

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

I have a simple form with four inputs. When I submit my form, I want to use the GET http method.

For the example :

aaa : foo
bbb : ____
ccc : bar
ddd : ____

I want to have this query string :

/?aaa=foo&ccc=bar

The problem is I have this query string :

/?aaa=foo&bbb=&ccc=bar&ddd=

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

Thanks.

Upvotes: 28

Views: 13135

Answers (7)

tklodd
tklodd

Reputation: 1079

Here's a very similar answer to the other ones, but it factors in select and textarea inputs as well:

$(document).ready(function() {
    
    $("form").submit(function() {
        
        let form = $(this);
        
        form.find('input, select, textarea').each(function() {
            let input = $(this);
            if (input.val() == '') {
                input.prop('disabled', true);
            }
        });
        
    });
    
 });

Upvotes: 1

Kathandrax
Kathandrax

Reputation: 1054

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.

Upvotes: 5

Lord Elrond
Lord Elrond

Reputation: 16032

If you want to remove all empty inputs, you can iterate over the form inputs like this:

<script type="text/javascript">
    $(document).ready(function() {
        $("#form1").submit(function() {
          $(this).find('input').each(function() {
            if($(this).val() == '') {
              $(this).remove();
            }
          });
        });
     });
</script>

Upvotes: 1

martti
martti

Reputation: 2067

With jQuery:

$('form[method="get"]').submit(function(){
    $(this).find(':input').each(function() {
        var inp = $(this);
        if (!inp.val()) {
            inp.remove();
        }
    });
});

I use this to remove all empty parameters from all GET forms on my site. The :input pseudo selector covers all inputs, textareas, selects and buttons.

Upvotes: 2

Hobbes
Hobbes

Reputation: 415

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.

Upvotes: 7

Haroon
Haroon

Reputation: 195

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)

Upvotes: 6

RaphDG
RaphDG

Reputation: 1371

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>

Upvotes: 13

Related Questions