【发布时间】:2014-08-20 02:35:07
【问题描述】:
如何使用 jQuery 在动态生成的选择控件中将选项设置为已选择?
我正在尝试使用 php、jquery、ajax 使用 php、jquery、ajax 构建一个带有动态选择字段的小型汽车搜索 [这样用户永远不能选择一组导致没有结果的选项!]
现在我只是为 ajax 提供一个用 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);
效果很好,我们可以在控制台中看到所有内容,
然后我们有它的javascript:
$('.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!!!');
}
});
});
函数 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
};
});
}
问题在于如何将选项设置为选中,我似乎无法弄清楚。弹出警报,但我不知道如何将循环中的当前选项设置为选中。
这是怎么做到的?
【问题讨论】:
-
试试
mycontrol.prop('selected', true);
标签: jquery