Skeen,

>I needed a simple method to populate field names with corresponding
>data from a database (for an "edit entry" interface). So I wrote the
>following function, which accepts 3 arguments: the ajax get request
>url, the form id, and new text for the form's submit button, if
>required:
>
>function populateFieldsWithJson(url, form, submit_text) {
>       $.ajax({
>               type: "GET",
>               url: url,
>               dataType: "json",
>               success: function(json) {
>                       $("#"+form+" input[type=text]").each(function() {
>                               var fieldName = $(this).attr("name");
>                               var getVal = "json."+fieldName;
>                               var value = eval(getVal);
>                               $(this).val(value);
>                               var submit_button = $("#"+form+"
>input[type=submit]");
>                               if (submit_text)
submit_button.val(submit_text);
>                       });
>               }
>       });
>}
>
>The request must return json data, with name/value pairs corresponding
>to your form fields. Some example data might be: { "name": "Michael",
>"phone": "555-1234" }
>
>This would populate the corresponding text fields of your form (in
>this example "name" and "phone"), with the specified data ("Michael",
>"555-1234").

I'd recommend you check out my Field Plug-in:
http://jquery.com/plugins/project/field

There's a jQuery method called formHash() which will populate a form based
on JS hash table/associative array/structure or whatever else you want to
call it. The hashForm() works on all field types (not just text fields) so
it works with checkboxes and radio elements.

Using the Field plug-in you could just write:

$.ajax({
        type: "GET",
        url: url,
        dataType: "json",
        success: function(json){
                $("#formName").hashForm(json);
        }
});

-Dan

Reply via email to