views:

6217

answers:

4

I have a search form with a number of text inputs & drop downs that submits via a GET. I'd like to have a cleaner search url by removing the empty fields from the querystring when a search is performed.

var form = $("form");  
var serializedFormStr = form.serialize();  
// I'd like to remove inputs where value is '' or '.' here
window.location.href = '/search?' + serializedFormStr

Any idea how I can do this using jQuery?

+1  A: 

I would look at the source code for jQuery. In the latest version line 3287.

I might add in a "serialize2" and "serializeArray2" functions. of course name them something meaniful.

Or the better way would be to write something to pull the unused vars out of the serializedFormStr. Some regex that looks for =& in mid string or ending in = Any regex wizards around?

UPDATE: I like rogeriopvl's answer better (+1)... especially since I can't find any good regex tools right now.

tyndall
A: 

You might want to look at the .each() jquery function, that allows you to iterate through every element of a selector, so this way you can go check each input field and see if it's empty or not and then remove it from the form using element.remove(). After that you can serialize the form.

rogeriopvl
The only problem with that is the user will see the empty from controls disappearing just before the page submits. Would be better to set the name to "" so serialize ignores it.
Tom Viner
@7times9, yes you're right, I forgot about that detail.
rogeriopvl
+1  A: 

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
nickf
Tom Viner
+12  A: 

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] matches elements that have the value attribute excluding empty values. 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()

[value!='.'] is an attribute not equal filter.

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!

Tom Viner