Skip to content Skip to sidebar Skip to footer

Use Jquery To Re-populate Form With JSON Data

I have an HTML form, that I save to the database via ajax. To get the query string of key/value pairs, I have used the very convenient serialize function, like this: var myData =

Solution 1:

I'd say the easiest way would be something along these lines:

// reset form values from json object
$.each(data, function(name, val){
    var $el = $('[name="'+name+'"]'),
        type = $el.attr('type');

    switch(type){
        case 'checkbox':
            $el.attr('checked', 'checked');
            break;
        case 'radio':
            $el.filter('[value="'+val+'"]').attr('checked', 'checked');
            break;
        default:
            $el.val(val);
    }
});

Basically, the only ones that are odd are the checkboxes and radios because they need to have their checked property, well, checked. The radios are a little more complex than the checkboxes because not only do we need to check them, we need to find the right ONE to check (using the value). Everything else (inputs, textareas, selectboxes, etc.) should just have its value set to the one that's returned in the JSON object.

jsfiddle: http://jsfiddle.net/2xdkt/


Solution 2:

If data[0] contains the name of the field and data[1] contains the value then you can do the following:

You can do something like this for text boxes:

$("[name="+data[0]+"]").val(data[1]);

Then something like this for selects:

$("[name="+data[0]+"]").val(data[1]);

Please note that check boxes and radio buttons are only serialized if they are checked.

So something like this for check boxes (before jQuery 1.6+):

$("[name="+data[0]+"]").attr('checked','checked');

The radio button might need some additional work depending on how you're differentiating between the different ones. (I.E. Id, value, etc..)


Solution 3:

I suggest you change the way you are making an ajax request. Use .post()

$.post("my_save_script.php", {
         data: myData,
    }, function(data) {
        $.each(data, function(i, item){
            $("#"+item.field).val(item.value);
        });      
    }, 
"json");

Post a Comment for "Use Jquery To Re-populate Form With JSON Data"