Sunday, May 12, 2024
 Popular · Latest · Hot · Upcoming
19
rated 0 times [  23] [ 4]  / answers: 1 / hits: 95088  / 16 Years ago, tue, march 3, 2009, 12:00:00

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?


More From » jquery

 Answers
23

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!


[#99894] Thursday, February 26, 2009, 16 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
stefanicarolinat

Total Points: 145
Total Questions: 91
Total Answers: 93

Location: Cambodia
Member since Thu, Oct 7, 2021
3 Years ago
stefanicarolinat questions
Mon, Nov 15, 21, 00:00, 3 Years ago
Fri, Apr 16, 21, 00:00, 3 Years ago
Thu, Oct 15, 20, 00:00, 4 Years ago
Fri, Jul 17, 20, 00:00, 4 Years ago
;