gpt4 book ai didi

所有输入的 jQuery 表单反序列化

转载 作者:行者123 更新时间:2023-12-01 00:16:27 24 4
gpt4 key购买 nike

我一直在使用一个简单的each函数来反序列化表单:

  data = { key : val, ... };
form = $('#formId');
$.each(data, function(val,i) {
form.find('*[name="' + val + '"]').val(data[val]);
});

但我似乎无法让它适用于非标准表单元素(即单选按钮/复选框)。我已经玩了几个小时的不同例子,但无法让它工作。有人知道一个优雅的解决方案吗?

最佳答案

试试这个:

example

html:

<form id="formId">
a: <input name="a" /><br />
b: <input name="b" /><br />
c: <input type="checkbox" name="c" /><br />
d: <select name="d"><option value="d1">d1</option><option value="d2">d2</option></select><br />
e: <input type="radio" value="1" name="e" /><br />
e: <input type="radio" value="2" name="e" /><br />
e: <input type="radio" value="3" name="e" /><br />
f: <input type="checkbox" name="f" /><br />
</form>

js:

var 
data = { a: "value for a", b: "value for b", c: false, d:"d2", e: "2", f:true },
form = $('#formId');

$.each(data, function(i, el) {

var
fel = form.find('*[name="' + i + '"]'),
type = "", tag = "";

if (fel.length > 0) {

tag = fel[0].tagName.toLowerCase();

if (tag == "select" || tag == "textarea") { //...
$(fel).val(el);
}
else if (tag == "input") {
type = $(fel[0]).attr("type");
if (type == "text" || type == "password" || type == "hidden") {
fel.val(el);
}
else if (type == "checkbox") {
if (el)
fel.attr("checked", "checked");
}
else if (type == "radio") {
fel.filter('[value="'+el+'"]').attr("checked", "checked");
}
}
}
})

关于所有输入的 jQuery 表单反序列化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5197090/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com