22

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

jeffery_the_wind
  • 17,048
  • 34
  • 98
  • 160
  • 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. – Tuan Mar 21 '12 at 15:32
  • Yes the `name` attribute of the of the form elements is the same as the key values of the JSON object. – jeffery_the_wind Mar 21 '12 at 15:34
  • 1
    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. – Tuan Mar 21 '12 at 15:42
  • 1
    what about check boxes, radio boxes and selects? – jeffery_the_wind Mar 21 '12 at 15:45
  • Good point about checkboxes and radio buttons. It will work for selects, but you'll need to handle checkboxes and radio buttons separately. – Tuan Mar 21 '12 at 15:55

3 Answers3

57

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/

Bryan B.
  • 897
  • 8
  • 8
  • 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. – Lonnie Best Dec 14 '12 at 18:22
  • 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! – mffap Jun 11 '13 at 14:23
  • 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! – Bryan B. Jun 11 '13 at 17:12
  • 1
    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);` – Mahmood Dehghan Jun 23 '13 at 06:09
  • Why are you always selecting checkboxes? attr('checked,'checked') - shouldn't that depend on the value of the individual checkbox? – gene b. Sep 19 '18 at 20:35
  • 1
    @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. – Bryan B. Sep 20 '18 at 17:14
0

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..)

evasilchenko
  • 1,862
  • 1
  • 13
  • 26
  • 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. – jeffery_the_wind Mar 21 '12 at 15:44
  • You mean if there was a deserialize() function? You can check out this plugin: http://code.google.com/p/jquery-nmx-deserialize/ it seems to be abandoned though... :( – evasilchenko Mar 21 '12 at 16:05
-1

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");
Starx
  • 77,474
  • 47
  • 185
  • 261