How do I use jQuery's form.serialize but exclu

2019-01-04 16:16发布

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?

8条回答
爱情/是我丢掉的垃圾
2楼-- · 2019-01-04 16:52

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();
查看更多
霸刀☆藐视天下
3楼-- · 2019-01-04 16:53

This works for me:

data = $( "#my_form input").filter(function () {
        return !!this.value;
    }).serialize();
查看更多
甜甜的少女心
4楼-- · 2019-01-04 16:55

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.

查看更多
Juvenile、少年°
5楼-- · 2019-01-04 16:56

I have used above solution but for me those did not worked. So I have used following code

$('#searchform').submit(function(){

            var serializedData = $(this).serializeArray();
            var query_str = '';

            $.each(serializedData, function(i,data){
                if($.trim(data['value'])){
                    query_str += (query_str == '') ? '?' + data['name'] + '=' + data['value'] : '&' + data['name'] + '=' + data['value'];
                }
            });
            console.log(query_str);
            return false;
        });

May be useful for someone

查看更多
不美不萌又怎样
6楼-- · 2019-01-04 16:59

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=ffffd&e=";
new => "b=bbb&d=ffffd&"  // dunno if that trailing & is a problem or not
查看更多
迷人小祖宗
7楼-- · 2019-01-04 17:10

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.

查看更多
登录 后发表回答