Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

bind JSON properties to a form

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

The form in question looks something like:

<form id = "#myform" action="/foo/bar/">
  <input name="foo"/>
  <input name="bar"/>
</form>
like image 959
Dónal Avatar asked Sep 08 '11 11:09

Dónal


2 Answers

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

like image 51
Benoît Avatar answered Sep 19 '22 18:09

Benoît


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];
}
like image 42
abraxas Avatar answered Sep 19 '22 18:09

abraxas