Use jquery to re-populate form with JSON data
Question by jeffery_the_wind
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
Answer by Bryan B.
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/
Answer by Starx
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");