I have a JSON object and a <form>
. If the JSON object has a property whose name matches the name of a form &l开发者_如何学编程t;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
The form in question looks something like:
<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);
});
and for the form:
<form id="myform">
<input type="text" name="foo" />
<input type="text" name="other" />
</form>
using .field instead of input is to work with textarea and select
You mean something like:
var json = {foo: 'foo', bar: 'bar};
def form = $('#myform');
for(var prop in json){
$("#myform input[name="+prop+"]")[0].value = json[prop];
}
try this:
var json = {foo: 'foo1', bar: 'bar1'};
for(var key in json) {
if($('#myform input[name="'+key+'"]').length > 0){
$('#myform input[name="'+key+'"]').attr('value',json[key]);
}
}
I think it's this what you want ;)
See example here: http://jsfiddle.net/expertCode/FgwHe/
You can use my plugin, its fairly simple: https://github.com/devWaleed/JQuery-JSON-Form-Binding
Callbacks are optional if you want to populate data in your own way.
$("#myform").jsonToForm({
data: {name: "Waleed", age: 23, gender: "Male"},
callbacks: {
age: function(value){
$('[name="age"]').val(value+1);
}
}
});
either you find all your inputs and get the inputs names and check them in they are in the json something like: http://jsbin.com/ulelik/edit .
var json = {foo: 'foo', bar: 'bar', ContactEmail: "ContactEmail", fooo2 : "trigunatmak kulkarni"};
var inputs = $('input', '#myform').each(function() {
if (json[this.name])
{
this.value = json[this.name];
}
});
you pick out all the inputs and check by their names if they have a property in the json object then it will use that property value as the input value.
精彩评论