我有一个包含 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="[{"Id":118},{"Id":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/