【问题标题】:How to set an option as selected in a dynamically generated select control using jQuery?如何使用jQuery在动态生成的选择控件中设置选项?
【发布时间】: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


【解决方案1】:

当您使用.append() 时,它返回目标元素返回的元素而不是附加元素(在您的情况下是select 元素而不是新添加的option 元素)。所以mycontrol.attr('selected','selected');这个语句没有任何作用。

你需要在新创建的option元素上设置selected属性,你可以使用appendTo() like

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-12-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-13
    • 1970-01-01
    • 2021-03-10
    • 2016-07-16
    相关资源
    最近更新 更多