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>
                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];
}
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With