kentor kentor - 4 months ago 19
jQuery Question

Serialize form as json without empty values

I have a HTML form with 3 fields. I want to serialize them as json object (that works so far using my

getFormData($form)
method. But now I want to exclude all fields without inputtext/value in my form.

This serializes my form and saves it as json object:

function getFormData($form){
var unindexed_array = $form.serializeArray();
var indexed_array = {};

$.map(unindexed_array, function(n, i){
indexed_array[n['name']] = n['value'];
});

return indexed_array;
}


This is how I tried to filter fields without value:

var form = $("#bulk-edit-fut-account-form :input[value!='']");
console.log(JSON.stringify(form));
var formData = getFormData(form);


My HTML form:

<form id="bulk-edit-fut-account-form" class="form-horizontal" novalidate="novalidate"><div class="form-group"><label class="col-sm-3 control-label">Id<span class="asterisk">*</span></label><div class="col-sm-9"><input id="bulkAccountIds" type="text" required="" readonly="" value="118 119 " data-id="[{&quot;Id&quot;:118},{&quot;Id&quot;:119}]" class="form-control valid" aria-required="true"></div></div><div class="form-group"><label class="col-sm-3 control-label">Max. Requests / minute</label><div class="col-sm-9"><input type="number" name="RequestsPerMinute" placeholder="Type maximum amount of reqs/min..." class="form-control valid"></div></div><div class="form-group"><label class="col-sm-3 control-label">Request Threshold</label><div class="col-sm-9"><input type="number" name="Threshold" placeholder="Type fastest timeframe for 1 request in seconds..." class="form-control valid"></div></div><div class="form-group"><label class="col-sm-3 control-label">Comment</label><div class="col-sm-9"><textarea name="Comment" rows="5" class="form-control"></textarea></div></div></form>


The problem:

Using the above code, it will still serialize empty fields (but I want to avoid that). This is the result
{ RequestsPerMinute: '121', Threshold: '', Comment: '' }
. How can I avoid serializing the fields without value?

Answer

Try this:

    var form = $(); //Initialize empty jQuery object

    //Iterate through all inputs, textareas
    $('#bulk-edit-fut-account-form input, #bulk-edit-fut-account-form textarea').each(function() {

        //Add to jQuery object if not empty
        if ($(this).val().length) {
           form = form.add($(this)); 
        }

    })

    console.log(JSON.stringify(form));
    var formData = getFormData(form);