开发者

jQuery serialize how to eliminate empty fields

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_submiss开发者_JAVA技巧ion.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?


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.


What i am using atm is

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


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.


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.


Try adding this

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

OR

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

before

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


Firstly do the check if your fields are not empty. These succesful push to the array. You may than serialize the array of elements.


This should work for what you're trying to do :

$(document).ready(function() {
    $('#submForm').validate({ 
        submitHandler: function(form) {
            // Do cleanup first
            $('#submForm>input').each(function(){
                if($(this).val() == "") { $(this).remove(); }
            });
            var serialized = $('#submForm').serialize();
            $.get('".$site['url']."modules/yobilab/copyright/classes/DO_submission.php', serialized);
            window.setTimeout('location.reload()', 8000);
            return false;
            form.submit(); 
        }
    })
});

Edit...
I really think Mark Koopman's solution would be the simplest option. Is there any reason why you can't use POST instead of GET?

Edit 2...
Oops, I totally missed that amit_g posted this same solution. But I hope at least seeing it in context was still helpful.


I just needed to do the same thing, so I wrote a little plugin that just disables empty inputs before serializing:

(function($) {
  $.fn.serialize_without_blank = function () {
    var $form = this,
      result,
      $disabled = $([]);

    $form.find(':input').each(function () {
      var $this = $(this);
      if ($.trim($this.val()) === '' && !$this.is(':disabled')) {
        $disabled.add($this);
        $this.attr('disabled', true);
      }
    });

    result = $form.serialize();

    $disabled.removeAttr('disabled');

    return result;
  };
}(jQuery));

Use like so:

$.ajax({
  url: $form.attr('action'),
  type: $form.attr('method'),
  data: $form.serialize_without_blank();
});


Dr.Molle solution works but if the value attribute is missing then this is the solution:-

$(form).clone().find("input").each(function() {
    if ($.trim($(this).val()) === '') {
        $(this).remove();
    }
}).end().serialize();


var serializedData = $('.register-form').serializeArray();
var clear = {};
$.each(serializedData , function(i,data) {                                       
if(data.value!=='' && clear[data.name]==undefined) clear[i] = data;                                      
                                    });


Here's what I did

var form = $('form');
var form_input = form.serialize().replace(/[^=&]+=(&|$)/g,"").replace(/&$/,"");
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜