使用 jQuery 和 JSON 来填充表单?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7298364/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Using jQuery and JSON to populate forms?
提问by Itai Sagi
I was wondering how is it popssible to populate forms using JSON?
我想知道如何使用 JSON 填充表单?
I have a JSON string which I get using php's json_encode()
And I want to use the JSON string to populate form controls (such as textarea or text input).
我有一个使用 php 获得的 JSON 字符串,我json_encode()
想使用 JSON 字符串来填充表单控件(例如 textarea 或文本输入)。
How can I achieve such thing without using external plugins (like jQuery populate plugin, which I saw).
我怎样才能在不使用外部插件的情况下实现这样的事情(比如我看到的 jQuery populate 插件)。
EDIT: JSON format:
编辑:JSON 格式:
[{"id":"41","parent_id":null,"node_name":"name","slug":"","lft":"3","rgt":"4"}]
This is what I get from json_encode()
这是我从 json_encode() 得到的
回答by Nowshath
There is a problem here with textarea
, then I change it to a default
switch value
这里有问题textarea
,然后我把它改成一个default
开关值
Use this to assign values to Many Controls :
使用它来为 Many Controls 分配值:
function populate(frm, data) {
$.each(data, function(key, value) {
var ctrl = $('[name='+key+']', frm);
switch(ctrl.prop("type")) {
case "radio": case "checkbox":
ctrl.each(function() {
if($(this).attr('value') == value) $(this).attr("checked",value);
});
break;
default:
ctrl.val(value);
}
});
}
回答by Guffa
For just text controls (i.e. no radios or checkboxes), you can make a simple version of a populate function:
对于文本控件(即没有单选框或复选框),您可以制作一个简单版本的填充函数:
function populate(frm, data) {
$.each(data, function(key, value){
$('[name='+key+']', frm).val(value);
});
}
Usage example:
用法示例:
populate('#MyForm', $.parseJSON(data));
回答by Alexander G
Thanks Nowshath. It worked for me. I added a extra check in your version to be able to populate select options as well.
谢谢诺沙。它对我有用。我在你的版本中添加了一个额外的检查,以便能够填充选择选项。
function populateForm(frm, data) {
$.each(data, function(key, value){
var $ctrl = $('[name='+key+']', frm);
if($ctrl.is('select')){
$("option",$ctrl).each(function(){
if (this.value==value) { this.selected=true; }
});
}
else {
switch($ctrl.attr("type"))
{
case "text" : case "hidden": case "textarea":
$ctrl.val(value);
break;
case "radio" : case "checkbox":
$ctrl.each(function(){
if($(this).attr('value') == value) { $(this).attr("checked",value); } });
break;
}
}
});
}; // end of populateForm() function
回答by Spiel
With little improvements (except radio buttons):
几乎没有改进(单选按钮除外):
function resetForm($form)
{
$form.find('input:text, input:password, input:file, select, textarea').val('');
$form.find('input:radio, input:checkbox').removeAttr('checked').removeAttr('selected');
}
function populateForm($form, data)
{
resetForm($form);
$.each(data, function(key, value) {
var $ctrl = $form.find('[name='+key+']');
if ($ctrl.is('select')){
$('option', $ctrl).each(function() {
if (this.value == value)
this.selected = true;
});
} else if ($ctrl.is('textarea')) {
$ctrl.val(value);
} else {
switch($ctrl.attr("type")) {
case "text":
case "hidden":
$ctrl.val(value);
break;
case "checkbox":
if (value == '1')
$ctrl.prop('checked', true);
else
$ctrl.prop('checked', false);
break;
}
}
});
};
回答by Nicholas
This is an apendix to @Nowshath's answer
这是@Nowshath 答案的附录
This works for multilevel objects as well
这也适用于多级对象
populateForm(form, data) {
$.each(data, function(key, value) {
if(value !== null && typeof value === 'object' ) {
this.populateForm(form, value);
}
else {
var ctrl = $('[name='+key+']', form);
switch(ctrl.prop("type")) {
case "radio": case "checkbox":
ctrl.each(function() {
$(this).prop("checked",value);
});
break;
default:
ctrl.val(value);
}
}
}.bind(this));
}
回答by iautomation
In case anyone is looking to populate from a multidimensional json format, such as the result of $.serializeJSON[ https://github.com/marioizquierdo/jquery.serializeJSON], here's a function to convert to a flat format.
如果有人希望从多维 json 格式填充,例如 $.serializeJSON[ https://github.com/marioizquierdo/jquery.serializeJSON]的结果,这里有一个转换为平面格式的函数。
function json2html_name_list(json, result, parent){
if(!result)result = {};
if(!parent)parent = '';
if((typeof json)!='object'){
result[parent] = json;
} else {
for(var key in json){
var value = json[key];
if(parent=='')var subparent = key;
else var subparent = parent+'['+key+']';
result = json2html_name_list(value, result, subparent);
}
}
return result;
}
Usecase example with the functions above:
具有上述功能的用例示例:
populateForm($form, json2html_name_list(json))
With all the examples above though:
有了上面的所有例子:
var $ctrl = $('[name='+key+']', frm);
needs to be changed to
需要改为
var $ctrl = $('[name="'+key+'"]', frm);
to prevent a syntax error with jQuery
防止 jQuery 出现语法错误
Take note list arrays have to be written with numbers(e.g. fruit[0], instead of fruit[]) in order to be work with this function.
注意列表数组必须用数字写入(例如fruit[0],而不是fruit[])才能使用此函数。
回答by batomaeus
I had the same problem and have developed the version shown above a little further. Now it is possible to have individual checkboxes that return the value as well as groups that returns an array of names. The coding is tested, used and working correctly.
我遇到了同样的问题,并进一步开发了上面显示的版本。现在可以有返回值的单个复选框以及返回名称数组的组。编码经过测试、使用并正常工作。
function populateForm($form, data)
{
//console.log("PopulateForm, All form data: " + JSON.stringify(data));
$.each(data, function(key, value) // all json fields ordered by name
{
//console.log("Data Element: " + key + " value: " + value );
var $ctrls = $form.find('[name='+key+']'); //all form elements for a name. Multiple checkboxes can have the same name, but different values
//console.log("Number found elements: " + $ctrls.length );
if ($ctrls.is('select')) //special form types
{
$('option', $ctrls).each(function() {
if (this.value == value)
this.selected = true;
});
}
else if ($ctrls.is('textarea'))
{
$ctrls.val(value);
}
else
{
switch($ctrls.attr("type")) //input type
{
case "text":
case "hidden":
$ctrls.val(value);
break;
case "radio":
if ($ctrls.length >= 1)
{
//console.log("$ctrls.length: " + $ctrls.length + " value.length: " + value.length);
$.each($ctrls,function(index)
{ // every individual element
var elemValue = $(this).attr("value");
var elemValueInData = singleVal = value;
if(elemValue===value){
$(this).prop('checked', true);
}
else{
$(this).prop('checked', false);
}
});
}
break;
case "checkbox":
if ($ctrls.length > 1)
{
//console.log("$ctrls.length: " + $ctrls.length + " value.length: " + value.length);
$.each($ctrls,function(index) // every individual element
{
var elemValue = $(this).attr("value");
var elemValueInData = undefined;
var singleVal;
for (var i=0; i<value.length; i++){
singleVal = value[i];
console.log("singleVal : " + singleVal + " value[i][1]" + value[i][1] );
if (singleVal === elemValue){elemValueInData = singleVal};
}
if(elemValueInData){
//console.log("TRUE elemValue: " + elemValue + " value: " + value);
$(this).prop('checked', true);
//$(this).prop('value', true);
}
else{
//console.log("FALSE elemValue: " + elemValue + " value: " + value);
$(this).prop('checked', false);
//$(this).prop('value', false);
}
});
}
else if($ctrls.length == 1)
{
$ctrl = $ctrls;
if(value) {$ctrl.prop('checked', true);}
else {$ctrl.prop('checked', false);}
}
break;
} //switch input type
}
}) // all json fields
} // populate form
回答by Ian Tearle
I found the original script didn't play nice with array[] names because of missing quotes in the name selector:
由于名称选择器中缺少引号,我发现原始脚本不能很好地处理数组 [] 名称:
var $ctrl = $('[name="'+key+'"]', frm);
回答by Matt
This can get pretty complicated. It's best to use a tool to parse your JSON. You can create simple forms pretty easily, but you still need to parse it.
这可能会变得非常复杂。最好使用工具来解析您的 JSON。你可以很容易地创建简单的表单,但你仍然需要解析它。
Check this plugin out instead: http://neyeon.com/2011/01/creating-forms-with-json-and-jquery/
请查看此插件:http: //neyeon.com/2011/01/creating-forms-with-json-and-jquery/
Or you can use ext4.
或者你可以使用ext4。
回答by saurshaz
For a weird but valid JSON syntax like
对于奇怪但有效的 JSON 语法,如
[{'name':<field_name>,'value':<field_value>},
{'name':<field_name>,'value':<field_value>},
{'name':<field_name>,'value':<field_value>},
{'name':<field_name>,'value':<field_value>}]
look at this http://jsfiddle.net/saurshaz/z66XF/
看看这个http://jsfiddle.net/saurshaz/z66XF/
We had this weird syntax being used in our application and we got around by writing the logic as above.
我们在我们的应用程序中使用了这种奇怪的语法,我们通过编写上述逻辑来解决。