如何使用jQuery在动态生成的选择控件中设置选项?
我试图用动态选择字段构建一个小汽车搜索[这样用户永远不会选择一组导致无结果的选项!]使用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!!!');
}
});
});
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
};
});
}
问题在于如何将选项设置为选中,我似乎无法想出那个选项。弹出警报但我不知道如何将循环中的当前选项设置为选中。
这是怎么做到的?
答案 0 :(得分:1)
当您使用.append()时,它返回返回目标元素的元素而不是附加元素(在您的情况下,select
元素不是新添加的option
元素)。所以声明mycontrol.attr('selected','selected');
没有任何效果。
您需要在新创建的option
元素上设置所选属性,为此您可以使用appendTo()
function populateSelectControls(optKey, optValues) {
var $control = $('#' + optKey);
$control.empty();
$control.append($("<option></option>").text('Select ' + optKey));
$.each(optValues, function (key, value) {
//the problem is here, in your case mycontrol was referring to the select not the added option
$("<option />", {
value: '.' + key,
text: key,
selected: value === 'selected'
}).appendTo($control);
});
}
演示:Fiddle