Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 944
Tom Viner Avatar asked Mar 03 '09 23:03

Tom Viner


People also ask

How do you serialize data in a form?

To serialize a FormData object into a query string, pass it into the new URLSearchParams() constructor. This will create a URLSearchParams object of encoded query string values. Then, call the URLSearchParams. toString() method on it to convert it into a query string.

How does form serialize work?

The serialize() method creates a URL encoded text string by serializing form values. You can select one or more form elements (like input and/or text area), or the form element itself. The serialized values can be used in the URL query string when making an AJAX request.

How do you serialize data in JavaScript?

In JavaScript, for example, you can serialize an object to a JSON string by calling the function JSON. stringify() . CSS values are serialized by calling the function CSSStyleDeclaration. getPropertyValue() .


2 Answers

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!

like image 166
Tom Viner Avatar answered Oct 30 '22 14:10

Tom Viner


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(); 
like image 26
Rich Avatar answered Oct 30 '22 13:10

Rich