jQuery 去除表单空值 serialize how to eliminate empty fields

1.  Try adding this

$('input', '#submForm').each(function(){
    $(this).val() == "" && $(this).remove();
})

OR

$('input:text[value=""]', '#submForm').remove();

before

var serialized = $('#submForm').serialize()

来源:http://stackoverflow.com/a/6240625

You cannot use attribute selector for value as it is a changing property.

2. Use .filter()

$(document).ready(function () {
    $('#myForm').submit(function () {
        $(this).find(":input").filter(function () {
            return $.trim(this.value).length > 0
        }).serialize();
        alert('JavaScript done');
    });
});

Demo: Fiddle

Note: just serializing the input fields does not change in form submission, it can be used only if the form is submitted via ajax.

If you want to do a normal form submission but want to remove the empty fields then use .remove()

$(document).ready(function () {
    $('#myForm').submit(function () {
        $(this).find(":input").filter(function () {
            return $.trim(this.value).length == 0
        }).remove();
        alert('JavaScript done');
    });
});

来源:http://stackoverflow.com/a/20189110

3. 我个人使用的是:

$('#submForm').find('input').not('[value=""]').serialize();

OR

$('#search').find('input, select').not('[value=""], [value="0"], [value="DESC"]').serialize();

来源:http://stackoverflow.com/a/12414286

 

本文:jQuery 去除表单空值 serialize how to eliminate empty fields

Leave a Reply