javascript - 将表单序列化为不带空值的 json

标签 javascript jquery node.js forms serialization

我有一个包含 3 个字段的 HTML 表单。我想将它们序列化为 json 对象(到目前为止,使用我的 getFormData($form) 方法有效。但现在我想排除表单中没有 inputtext/value 的所有字段。

这会序列化我的表单并将其保存为 json 对象:

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;
}

这就是我尝试过滤没有值的字段的方法:

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

我的 HTML 表单:

<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>

问题:

使用上面的代码,它仍然会序列化空字段(但我想避免这种情况)。这是结果 { RequestsPerMinute: '121', Threshold: '', Comment: '' } 。如何避免序列化没有值的字段?

最佳答案

这是修改函数的一种方法

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

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

    if (no_empty) {
        $.each(indexed_array, function(key, value) {
            if ( $.trim(value) === "" ) delete indexed_array[key];
        });
    }

    return indexed_array;
}

当您不想正常调用它并包含所有内容时,您只需这样做

 var json = getFormData( form );

当你不想要空输入时,你就这样做

 var json = getFormData( form, true );

它们被过滤掉了

关于javascript - 将表单序列化为不带空值的 json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38729527/

相关文章:

javascript - 使用 Jquery 设置时,占位符在 IE 11 中不起作用

javascript - 选择多个 li,它是使用 jquery 的第一个 child

node.js - 差异 websocket.io socket.io

node.js - 尝试通过 Node js将zip文件上传到azure存储

javascript - 如何使用 Javascript 将图像对象转换为文件对象

javascript - 如何从 HTML 页面中提取完整的 DOM 树

javascript - 为什么 props 在 render 和 componentWillReceiveProps 中显示不同的值?

javascript - 渲染没有返回任何内容;尝试重定向到主页

javascript - 如何使用 webpack 更新多个捆绑的 js 文件?

javascript - mouseEvent.initMouseEvent 的参数不足