How do I use jQuery's form.serialize but exclude empty fields

I've been looking over the jQuery docs and I think we can do this in one line using selectors:

$("#myForm :input[value!='']").serialize() // does the job!

Obviously #myForm gets the element with id "myForm" but what was less obvious to me at first was that the space character is needed between #myForm and :input as it is the descendant operator.

:input matches all input, textarea, select and button elements.

[value!=''] is an attribute not equal filter. The weird (and helpful) thing is that all :input element types have value attributes even selects and checkboxes etc.

Finally to also remove inputs where the value was '.' (as mentioned in the question):

$("#myForm :input[value!=''][value!='.']").serialize()

In this case juxtaposition, ie placing two attribute selectors next to each other, implies an AND. Using a comma implies an OR. Sorry if that's obvious to CSS people!


I wasn't able to get Tom's solution to work (?), but I was able to do this using .filter() with a short function to identify empty fields. I'm using jQuery 2.1.1.

var formData = $("#formid :input")
    .filter(function(index, element) {
        return $(element).val() != '';
    })
    .serialize();

You could do it with a regex...

var orig = $('#myForm').serialize();
var withoutEmpties = orig.replace(/[^&]+=\.?(?:&|$)/g, '')

Test cases:

orig = "a=&b=.&c=&d=.&e=";
new => ""

orig = "a=&b=bbb&c=.&d=ddd&e=";
new => "b=bbb&d=ddd&"  // dunno if that trailing & is a problem or not