是否有一个jQuery插件可以序列化表单,然后在给定序列化值后恢复/填充表单?我知道表单插件可以序列化为查询字符串,但是我还没有发现任何可以从查询字符串中还原表单的内容。
我想做的是序列化表单值,每当表单更改时都存储为cookie,然后在首次加载页面时从cookie(如果存在)中恢复表单。
我已经找到了这个难题的一部分(表单插件,cookie插件,各种无法保存的自动保存插件),但是在我将各个部分拼凑起来之前,我想确保没有一个好的罐装解决方案在等待为我在那里。
谢谢!
吉姆
这是我根据其他人的工作推出的一些内容,特别是serializeAnything:
/* jQuery.values: get or set all of the name/value pairs from child input controls
* @argument data {array} If included, will populate all child controls.
* @returns element if data was provided, or array of values if not
*/
$.fn.values = function(data) {
var els = $(this).find(':input').get();
if(typeof data != 'object') {
// return all data
data = {};
$.each(els, function() {
if (this.name && !this.disabled && (this.checked
|| /select|textarea/i.test(this.nodeName)
|| /text|hidden|password/i.test(this.type))) {
data[this.name] = $(this).val();
}
});
return data;
} else {
$.each(els, function() {
if (this.name && data[this.name]) {
if(this.type == 'checkbox' || this.type == 'radio') {
$(this).attr("checked", (data[this.name] == $(this).val()));
} else {
$(this).val(data[this.name]);
}
}
});
return $(this);
}
};
Ive用以下内容扩展了Barnabas的答案:
- 支持具有相同名称的多个输入(通常会使用复选框)。
-
尽可能缓存选择器,删除不必要的$
/* jQuery.values: get or set all of the name/value pairs from child input controls * @argument data {array} If included, will populate all child controls. * @returns element if data was provided, or array of values if not */ $.fn.values = function(data) { var els = this.find(':input').get(); if(arguments.length === 0) { // return all data data = {}; $.each(els, function() { if (this.name && !this.disabled && (this.checked || /select|textarea/i.test(this.nodeName) || /text|hidden|password/i.test(this.type))) { if(data[this.name] == undefined){ data[this.name] = []; } data[this.name].push($(this).val()); } }); return data; } else { $.each(els, function() { if (this.name && data[this.name]) { var names = data[this.name]; var $this = $(this); if(Object.prototype.toString.call(names) !== '[object Array]'){ names = [names]; //backwards compat to old version of this code } if(this.type == 'checkbox' || this.type == 'radio') { var val = $this.val(); var found = false; for(var i = 0; i < names.length; i++){ if(names[i] == val){ found = true; break; } } $this.attr("checked", found); } else { $this.val(names[0]); } } }); return this; } };
感谢Barnabas Kendall的初始功能和EggertJóhannesson的单选按钮修复功能!
我遇到了复选框问题,如果未选中它们,则不会将其放入数组中,到目前为止效果很好。但是由于未选中复选框的状态不会存储,因此如果用户在编辑表单时选中了复选框,则无法恢复此状态。
因此,我扩展了还原功能,以取消选中不在数据数组中的所有复选框,这将确保无论在执行还原之前表单中进行了什么更改,复选框的状态都能正确还原:
if (this.name && data[this.name]) {
if(this.type == "checkbox" || this.type == "radio") {
$(this).prop("checked", (data[this.name] == $(this).val()));
} else {
$(this).val(data[this.name]);
}
} else if (this.type == "checkbox") {
$(this).prop("checked", false);
}
完整功能:
$.fn.values = function(data) {
var inps = $(this).find(":input").get();
if(typeof data != "object") {
// return all data
data = {};
$.each(inps, function() {
if (this.name && (this.checked
|| /select|textarea/i.test(this.nodeName)
|| /text|hidden|password/i.test(this.type))) {
data[this.name] = $(this).val();
}
});
return data;
} else {
$.each(inps, function() {
if (this.name && data[this.name]) {
if(this.type == "checkbox" || this.type == "radio") {
$(this).prop("checked", (data[this.name] == $(this).val()));
} else {
$(this).val(data[this.name]);
}
} else if (this.type == "checkbox") {
$(this).prop("checked", false);
}
});
return $(this);
}
};
非常感谢Barnabas Kendall的回答,非常有用。
但是我发现其中有1个关于恢复单选按钮的错误,而不是选择正确的单选按钮,而是将保存的值复制到组中的所有按钮。
幸运的是,修复很简单。只需更换
if(this.type == 'checkbox') {
用
if(this.type == 'checkbox' || this.type == 'radio') {
它将正确更新单选按钮
- 支持具有相同名称的多个输入(通常会使用复选框)。
- 尽可能缓存选择器
- 返回所有输入的值,如果设置
checkbox
或未radio
设置,则值为null
-
禁用
checkbox
或radio
如果值为null
$.fn.formData = function(values) { var form = $(this); var inputs = $(':input', form).get(); var hasNewValues = typeof values == 'object'; if (hasNewValues) { $.each(inputs, function() { var input = $(this); var value = values[this.name]; if (values.hasOwnProperty(this.name)) { switch (this.type) { case 'checkbox': input.prop('checked', value !== null && value); break; case 'radio': if (value === null) { input.prop('checked', false); } else if (input.val() == value) { input.prop("checked", true); } break; default: input.val(value); } } }); return form; } else { values = {}; $.each(inputs, function() { var input = $(this); var value; switch (this.type) { case 'checkbox': case 'radio': value = input.is(':checked') ? input.val() : null; break; default: value = $(this).val(); } values[this.name] = value; }); return values; } };
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
看看我的jQuery Populate插件:
http://www.keyframesandcode.com/code/development/javascript/jquery-populate-plugin/
填充所有表单元素以及标签和任何包含的HTML元素。
如果您需要处理这种情况:<input name="this[is][my][input][]" />
-贪婪的人需要解析整个矩阵:
要填充:
http://www.keyframesandcode.com/resources/javascript/jQuery/demos/populate-demo.html
要检索值:
使用$('form').serialize()
结果并将其传递给此函数:
http://phpjs.org/functions/parse_str/
要序列化到一个字符串:var s = $('form').first().serialize();
要基于该字符串进行还原:$('form').first().deserialize(s);
当然,您需要一个反序列化插件,例如我最初在此处发布的插件。
$.fn.deserialize = function (serializedString)
{
var $form = $(this);
$form[0].reset();
serializedString = serializedString.replace(/\+/g, '%20');
var formFieldArray = serializedString.split("&");
// Loop over all name-value pairs
$.each(formFieldArray, function(i, pair){
var nameValue = pair.split("=");
var name = decodeURIComponent(nameValue[0]);
var value = decodeURIComponent(nameValue[1]);
// Find one or more fields
var $field = $form.find('[name=' + name + ']');
// Checkboxes and Radio types need to be handled differently
if ($field[0].type == "radio" || $field[0].type == "checkbox")
{
var $fieldWithValue = $field.filter('[value="' + value + '"]');
var isFound = ($fieldWithValue.length > 0);
// Special case if the value is not defined; value will be "on"
if (!isFound && value == "on") {
$field.first().prop("checked", true);
} else {
$fieldWithValue.prop("checked", isFound);
}
} else { // input, textarea
$field.val(value);
}
});
return this;
}
更多信息:https : //stackoverflow.com/a/24441276/1766230
这是一个jsfiddle,可让您试用设置值,清除,重置和“反序列化”:http : //jsfiddle.net/luken/4VVs3/
文章标签:forms , jquery , serialization
版权声明:本文为原创文章,版权归 admin 所有,欢迎分享本文,转载请保留出处!
评论已关闭!