Set form inputs based on json object
In my code I have a JSON serialized dictionary like so:
{ BackgroundColor="F4F4F4", ShowTitle=true, NumberToShow=10}
I need to set the values of matching form fields (using the property key).
Here's how I'm doing it currently:
function applyPreset(preset) {
开发者_开发知识库 for (var prop in preset) {
var $container = $("div#attribute-" + prop);
$("input", $container).val(preset[prop]);
}
}
This works fine for textboxes but obviously doesn't work for radio checkboxes or select lists.
I wondered if there were any clever functions in jQuery to do this or should I just loop through each input, check it's type and set the value accordingly?
Please try this:
$(":radio", $container).attr('checked',preset[prop]);
$("select", $container).val(preset[prop]).change();
for checkbox
$(':checkbox').attr('checked', true);
OR
$(':checkbox').prop('checked', true);
should work.
精彩评论