views:

208

answers:

3

I'm sure I'm just missing something, but it would be really helpful if someone knows of a way to do this without calling a jquery plugin.

Let's suppose I have a simple html form like the following:

<form id="mainform" action="form.php" method="post">
    <fieldset>
    <legend>Main Form</legend>
        <label for="input1">First Input</label>
        <input id="input1" name="input1" type="text" />
        <label for="input2">First Input</label>
        <input id="input2" name="input2" type="text" />
    </fieldset>
</form>

And I have an ajax function, via jquery, that I want to fill in the above form. Not just the values, but also whether it's read-only, the class of the input, and whether it's disabled.

So the server is going to return all of this to the ajax function in json format, which should look something like:

{"input1":{"value":10},"input2":{"value":100,"readonly":"readonly","class":"noinput"}}

Is there a simple way of having jquery go through each top-level object, tie it to the DOM element with the corresponding ID and then set all sub-objects as attributes for that ID?

Sorry if this is a no-brainer. I'm not finding the right way to deal with json in the main jquery pages.

+1  A: 

You don't need any plugins:

$.post("/page/",
    "",
    function(json){
        try{

        //relevant part
        for(element in json){
            $(element).val(json[element]);
        }
        //end of relevant part

        }catch(e){alert(e.description);}
    }, "json");


Matt's answer is correct, I misread the json response. This is a simpler handler, as it only takes into account the text values of the elements.

voyager
+2  A: 
for(var element in json){
    for(var attribute in json[element]){
        $('#' + element).attr(attribute, json[element][attribute]);
    }
}
Matt
I think this looks good. Thanks! And setting the "value" attribute is as good as setting the `element.val()`, right?
Anthony
Yes, settings $('#input1').attr('value', 123) will set the value of the field.
Matt
A: 

How about this?

jQuery.each(jsonObject, function(input_idx, input_val)
{
    var input = $('#' + input_idx);
    jQuery.each(input_val, function(attr_idx, attr_val)
    {
        input.attr(attr_idx, attr_val);
    });
});

Or you can just use simple for loops:

for (var input_idx in jsonObject)
{
    var input_val = jsonObject[input_idx];
    var input = $('#' + input_idx);
    for (var attr_idx in input_val)
    {
        input.attr(attr_idx, input_val[attr_idx]);
    });
});
DrJokepu