Setting form input based on json object

In my code, I have a serialized JSON dictionary, for example:

{ BackgroundColor="F4F4F4", ShowTitle=true, NumberToShow=10} 

I need to set the values โ€‹โ€‹of the corresponding form fields (using the property key).

Here's how I do it now:

  function applyPreset(preset) { for (var prop in preset) { var $container = $("div#attribute-" + prop); $("input", $container).val(preset[prop]); } } 

This works great for text boxes, but obviously does not work for radio flags or lists.

I was wondering if there are any smart functions in jQuery for this or should I just scroll through each input, check its type and set the value accordingly?

+4
source share
1 answer

Please try the following:

 $(":radio", $container).attr('checked',preset[prop]); $("select", $container).val(preset[prop]).change(); 

for flag

 $(':checkbox').attr('checked', true); 

OR

 $(':checkbox').prop('checked', true); 

must work.

+3
source

All Articles