Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use jquery to re-populate form with JSON data

Tags:

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

like image 853
jeffery_the_wind Avatar asked Mar 21 '12 15:03

jeffery_the_wind


1 Answers

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/

like image 178
Bryan B. Avatar answered Oct 16 '22 15:10

Bryan B.