开发者

jQuery serialize remove empty Select

开发者 https://www.devze.com 2023-03-10 13:37 出处:网络
I have a big form, that will be serialized by a jQuery function. The problem is that I need to remove from this form before being serialized all the empty values.

I have a big form, that will be serialized by a jQuery function.

The problem is that I need to remove from this form before being serialized all the empty values.

I found a way to successfully remove all the empty input text fields, but not the selections.

It does not work properly with select dropdowns.

Ceck below:

echo "<script type=\"text/javascript\">
$(document).ready(function() {
    $('#submForm').validate({ 
        submitHandler: function(form) {
            // Do cleanup first
            $('input:text[value=\"\"]', '#submForm').remove();
            $('select option:empty', '#submForm').remove();
            var serialized = $('#submForm').serialize();
             $.get('".$moduleURL."classes/DO_submission.php', serialized);
            window.setTimeout('location.reload()', 8000);
            return false;
            form.submit(); 
        }
   开发者_如何学C })
});

It should completely remove the dropdown selections where the values are empty. Not only the options but the entire select box should not be included in the serialize function.

How do I achieve this?

$('select option:empty', '#submForm').remove();

This code is not working as it should..


First, a select can not have an empty value. It will default to the first option if the selected attribute is not set.

Second, $('select option:empty') selects the empty options. To do something, an option should have a value, so afaik the selector will never work.

What you need to do is check all selects to see if they have a different value than their default, and if it is not the case, remove them.


If with 'empty select' you mean that the user has not chosen a 'valid' option (for example the fist option of a select is <option value=''>Select your value</option> )why don't you iterate on the select and check their value?

$('select').each(function(){
    if ($(this).val() === ''){//this assumes that your empty value is ''
       $(this).remove();
    }
});

EDIT - sorry for the error, i missed the last parenthesis, i tried it and it works for me


I would just instead of serlizing the the whole form I would use jquery Form and then all you have to do is call

 $('#submForm').ajaxSubmit({/.../});


Try

$('select option:selected:empty').parent().remove(); 

Edited after reading Nicola's comment.

0

精彩评论

暂无评论...
验证码 换一张
取 消