Use jquery to re-populate form with JSON data

34,423

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/

Share:
34,423

Related videos on Youtube

jeffery_the_wind
Author by

jeffery_the_wind

Currently a Doctoral student in the Dept. of Math and Stats at Université de Montréal. In the past I have done a lot of full stack development and applied math. Now trying to focus more on the pure math side of things and theory. Always get a lot of help from the Stack Exchange Community! Math interests include optimization and Algebra although in practice I do a lot of machine learning.

Updated on April 17, 2020

Comments

  • jeffery_the_wind
    jeffery_the_wind about 4 years

    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 = $("form#form_id").serialize();
    $.ajax({
        url: "my_save_script.php",
        type: "post",
        data: myData,
        success: function(msg){
            alert(msg);
        }
    });
    

    Now I want to load a blank form, and re-populate it with the data from the database, which is delivered from an ajax call as a JSON string. I have been able to get a Javascript object with the correct key/value pairs like this:

    data = $.parseJSON(data);
    data = data[0];
    

    What is the simplest, most elegant way to re-populate the form?

    keep in mind the input elements of the form are text, select, checkbox, and radio. The names of the input elements are the same as the names of the database columns, and are the keys of the key/value pairs in the above data object. This is why the serialize function works so well for me

    • Tuan
      Tuan about 12 years
      You can do this in a simple way only if you setup a convention, such as assigning your form elements' ids with the key values of the JSON object you receive. In other words, the form and the server should adhere to some standard convention. If so, you can then iterate over the data to find and populate each form element.
    • jeffery_the_wind
      jeffery_the_wind about 12 years
      Yes the name attribute of the of the form elements is the same as the key values of the JSON object.
    • Tuan
      Tuan about 12 years
      In that case, you can try something like for (var key in data) { $("[name='" + key + "']").val(data[key]); }. This will populate your form elements with the received object's properties. If you receive a key-value array, you need to iterate over the array instead.
    • jeffery_the_wind
      jeffery_the_wind about 12 years
      what about check boxes, radio boxes and selects?
    • Tuan
      Tuan about 12 years
      Good point about checkboxes and radio buttons. It will work for selects, but you'll need to handle checkboxes and radio buttons separately.
  • jeffery_the_wind
    jeffery_the_wind about 12 years
    thank you, yes I know how to set each element individually, but this means i need an if ... elif ... elif ... else filter for the 4 kinds of input elements. That is OK, and is how I am doing it now, I just didn't know if there was a quick easy way to do it, just like the serialize functions saved a lot of coding when saving data from the form.
  • evasilchenko
    evasilchenko about 12 years
    You mean if there was a deserialize() function? You can check out this plugin: code.google.com/p/jquery-nmx-deserialize it seems to be abandoned though... :(
  • Lonnie Best
    Lonnie Best over 11 years
    Hey thanks for this. You saved me some time. I'm getting plus signs instead of spaces populated to the form, but that's a minor tweak. Thanks again.
  • mffap
    mffap almost 11 years
    Why didn't you use the same for radio and checkboxes? If i have a checkbox that should be checked given a specific value $el.filter('[value="'+val+'"]').attr('checked', 'checked'); works perfectly. Nice code, thank you!
  • Bryan B.
    Bryan B. almost 11 years
    My thinking was that for checkboxes, the name should uniquely identify the element in a given form. Since radio elements would typically share the name attribute, I only want to perform the more intense value attribute filter if I absolutely have to. But you're right, it should work equally well for checkboxes. Glad you found it useful!
  • Mahmood Dehghan
    Mahmood Dehghan almost 11 years
    For jQuery 1.6+: $el.prop('checked', true);. and also if json value is boolean (my case) it have to be: $el.prop('checked', val);
  • gene b.
    gene b. over 5 years
    Why are you always selecting checkboxes? attr('checked,'checked') - shouldn't that depend on the value of the individual checkbox?
  • Bryan B.
    Bryan B. over 5 years
    @geneb. My initial thought was that only checkboxes that are checked will submit their values. So if the name corresponding to a checkbox shows up in our data object, it was by definition checked before. I think that was a little naive on my part, though, because the data returned from the database will no doubt have all values represented. In that scenario, I think Mahmoodvcs comment above should do the trick.