jQuery serialize how to eliminate empty fields

18,441

Solution 1

Try adding this

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

OR

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

before

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

Solution 2

I just ran into this same issue, but with a much different type of form. I didn't like how several of the answers in here removed form elements, which you could see the elements removed on the page before the form submitted. Others cloned the form, which wasn’t returning any results for me with one of the forms.

So I ended up with this:

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

In my case, the above code worked on my selected menus as well as the input fields.

Here’s exactly what I used:

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

So it only pulled form fields that have data and not any default values. I'm curious to know if this can be optimized any further.

Solution 3

What i am using atm is

$("form").serialize().replace(/[^&]+=&/g, '').replace(/&[^&]+=$/g, '')

Solution 4

You might make use of a filter and the fact the serialize can be called on any jQuery object (this example is only meant to show that you can serialize only non-empty elements and only includes <input> elements from the form):

var serialized = $('#submForm').filter(function(){
                    return $(this).val();
                }).serialize();

Here's a working example - leave one or more text boxes empty and click the button; you will see the serialized string changes to include only the non-empty text boxes.

Solution 5

As the value attribute contains the default value, not the actual one, I considered using this:

var queryString = $('form input').map(function () {
        return $(this).val().trim() == "" ? null : this;
    }).serialize();

Advantages:

  • Trim the actual value, so spaces / tabulation won't be considered as true,
  • It doesn't modify the DOM element, so in case of fail, it's still reusable.
Share:
18,441

Related videos on Youtube

DiegoP.
Author by

DiegoP.

Updated on June 04, 2022

Comments

  • DiegoP.
    DiegoP. almost 2 years

    In this form users can add some info for Authors (music, lyric authors)

    The users have the option to add 1 or more authors.

    The problem is that when the user enters only 1 author all the other inputs remain empty, but the jQuery serialize function will put them anyway in the URL and the server gives me this error:

    Request-URI Too Large
    

    See the below example:

    echo "<form action=\"\" id=\"submForm\" name=\"submForm\" method=\"get\">";
    // AUTHOR NUMBER 1
    echo "<p><span class=\"labelInput\">".(_t('_cR_name'))." </span><input id=\"nameAuthor\" name=\"author[0][name]\" value=\"\" type=\"text\" class=\"commonInput\"></p>"; 
    echo "<p><span class=\"labelInput\">".(_t('_cR_DOB'))." </span><input id=\"DOBAuthor\" name=\"author[0][DOB]\" value=\"\" type=\"text\" class=\"littleInput\"></p>"; 
    echo "<p><span class=\"labelInput\">".(_t('_cR_DOD'))." </span><input id=\"DODAuthor\" name=\"author[0][DOD]\" value=\"\" type=\"text\" class=\"littleInput\"></p>"; 
    // AUTHOR NUMBER 2
    echo "<p><span class=\"labelInput\">".(_t('_cR_name'))." </span><input id=\"nameAuthor\" name=\"author[1][name]\" value=\"\" type=\"text\" class=\"commonInput\"></p>";
    echo "<p><span class=\"labelInput\">".(_t('_cR_DOB'))." </span><input id=\"DOBAuthor\" name=\"author[1][DOB]\" value=\"\" type=\"text\" class=\"littleInput\"></p>"; 
    echo "<p><span class=\"labelInput\">".(_t('_cR_DOD'))." </span><input id=\"DODAuthor\" name=\"author[1][DOD]\" value=\"\" type=\"text\" class=\"littleInput\"></p>"; Death:
    // AUTHOR NUMBER 3
    echo "<p><span class=\"labelInput\">".(_t('_cR_name'))." </span><input id=\"nameAuthor\" name=\"author[2][name]\" value=\"\" type=\"text\" class=\"commonInput\"></p>"; 
    echo "<p><span class=\"labelInput\">".(_t('_cR_DOB'))." </span><input id=\"DOBAuthor\" name=\"author[2][DOB]\" value=\"\" type=\"text\" class=\"littleInput\"></p>"; 
    echo "<p><span class=\"labelInput\">".(_t('_cR_DOD'))." </span><input id=\"DODAuthor\" name=\"author[2][DOD]\" value=\"\" type=\"text\" class=\"littleInput\"></p>"; 
    echo "</form>"; 
    

    And this is the jQuery code (it includes also a validate function, I am on jQuery 1.3.2)

    echo "<script type=\"text/javascript\">
    $(document).ready(function() {
     $('#submForm').validate({   
      submitHandler: function(form) {
      var serialized = $('#submForm').serialize()
      $.get('".$site['url']."modules/yobilab/copyright/classes/DO_submission.php', serialized);
        window.setTimeout('location.reload()', 8000);
    return false;
      form.submit();    
      } 
    })
    });
    

    Now let's say the user will enter the fields ONLY for AUTHOR 1 and will leave AUTHOR 2 and AUTHOR 3 empty. How do I say to the jQuery serialize function to include in the URL ONLY the entered fields and to NOT include the empty fields at all?

  • DiegoP.
    DiegoP. almost 13 years
    In code please. I am not a jQuery programmer. I do not anything about jQuery..please..Thank you
  • JamesWilson
    JamesWilson about 9 years
    This is really the best solution on this thread. It's a shame there aren't more +1's, you get my vote Bigood :)
  • JamesWilson
    JamesWilson about 9 years
    Instead of cloning the form to get around removing fields from the DOM, @Bigood has a smarter solution: stackoverflow.com/a/21558837/413538
  • Admin
    Admin about 8 years
    selector solutions did not work for me, this worked as expected! thanks.
  • Andreas
    Andreas almost 8 years
    this is not a good solution, because it changes the dom and might cause element flipping. If the ajax fails for whatever reasons, it will cause trouble with the form and also general usability.