Update page using JSON data
updateWithJSON is a jQuery plugin that updates elements on your page based on key/value pairs in a JSON object. Usage:
$.updateWithJSON(jsonData)
- iterate over each property/value combination in the JSON object
- look for an element in the DOM that matches the property name
- first, look for an element with a matching
idattribute - if no element with a matching ID is found, look for input, select or textarea elements with a matching
nameattribute
- first, look for an element with a matching
- update the value, contents or selection of the matched element(s) based on the value in the JSON object
name attribute, or a select that allows multiple values, you'll need to pass the values of the selected items in an array:
{
text_input: 'value1',
checkbox_group: ['value1','value2','value3'],
multi_select: ['value4','value5','value6']
}name attribute like "input[]" on a set of related checkboxes, remember that you'll need to quote it in the JSON object:
{
'input1[]': ['value1','value2','value3']
}The back story
For a recent project, I needed to update elements on a page based on some server-side calculations. JSON is a handy way to transport data from the server back to the browser, and jQuery'sgetJSON() method makes it painless. So, for example, I was getting back
{ foo: 'bar' }$.each(data,function(name,value) {
$('#'+name).val(value);
}name attribute on related checkboxes. Having checkboxes with the same name but different IDs can quickly get confusing when you're dealing with data on the client side and on the server side. The solution above worked in my particular case, but I wanted something that would work more broadly -- say, on pages that had related checkboxes -- and that's how I came up with the plugin.
1 comment
(1).When the value textarea is not changed after page load, it works;
(2).When the value textarea is changed by jQuery(through firebug), it works;
(3).When the value textarea is changed by keyboard input, it does NOT works;
(but case (3) works is in a IE6 browser.
cheers