将JSON属性绑定到表单 [英] bind JSON properties to a form
本文介绍了将JSON属性绑定到表单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个JSON对象和一个<form>
.如果JSON对象具有其名称与表单<input>
的名称匹配的属性,则我希望输入显示此属性的值.有没有使用JQuery做到这一点的简单方法?
I have a JSON object and a <form>
. If the JSON object has a property whose name matches the name of a form <input>
I want the input to display the value of this property. Is there a simple way to do this with JQuery?
var json = {foo: 'foo', bar: 'bar};
def form = $('#myform');
// something magical that assigns JSON property values to form inputs with matching names
有问题的表格如下:
<form id = "#myform" action="/foo/bar/">
<input name="foo"/>
<input name="bar"/>
</form>
推荐答案
您可以运行一个循环,该循环将搜索元素并输入值:
You can run a loop that will search the elment and put the value:
$.each(json,function(key,value) {
form.find("input[name='"+key+"']").val(value);
});
和形式:
<form id="myform">
<input type="text" name="foo" />
<input type="text" name="other" />
</form>
使用.field代替输入是为了处理文本区域并选择
using .field instead of input is to work with textarea and select
这篇关于将JSON属性绑定到表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文