How do I set an option as selected in a dynamically generated select control using jQuery?
I'm trying to build a little car search with dynamic select fields [so that a user can never select a set of options that result in no results!] using php, jquery, ajax
Right now I'm just feeding the ajax a static array populated with php:
$output = array( 'make' => array( 'GMC' => '', 'Chevy' => 'selected', 'NISSAN' => '', ), 'model' => array( 'Canyon' => '', 'Tahoe' => 'selected', 'Avalance' => '', ), 'year' => array( '2009' => '', '2010' => 'selected', '2011' => '', ), 'type' => array( 'Truck' => '', 'Mini Van' => 'selected', 'Compact' => '', ), ); $output = $modx->toJSON($output); which works fine, we can see everything coming through in the console,
Then we have the javascript for it:
$('.filter-group').change(function() {
var form = $('#searchform'); $.ajax({ type: "POST", //url: form.attr( 'action' ), url: '[[~131]]', data: form.serialize(), dataType : "json", cache: false, beforeSend: function() { console.log( 'before send' ); }, success: function(data, status) { $.each(data, function( key, value ) { console.log(key); populateSelectControls(key, value); }); }, error: function(data){ //this would be a 404 error! console.log('hellooo - this is an error!!!'); } }); });
function populateSelectControls(optKey, optValues){
var $control = $('#' + optKey); $control.empty(); $control.append($("<option></option>").text('Select ' + optKey)); $.each(optValues, function(key, value) { console.log('key = ' + key + ' value = ' + value); var mycontrol = $control.append($("<option></option>").attr("value", '.'+key).text(key)); if (value === 'selected') { alert(key + ' is selected'); mycontrol.attr('selected','selected'); // this is the problem }; }); }
The problem comes with how to set an option as selected, I can't seem to figure that one out. The alert pops up but I don't know how to set the current option in the loop to selected.
how is this done?
mycontrol.prop('selected', true);