【问题标题】:Append option in multiple select在多选中附加选项
【发布时间】:2015-02-22 13:30:18
【问题描述】:

我想在多选中附加选项,选项值来自ajax响应 我将 jquery-select2 用于多个选择字段 我的脚本代码

$.ajax({    
                type: "POST",
                data: {'tc_agency_code': agencycode,'tc_agency_name': agencyname,'tc_agency_address':address,'tc_contact_no':contactno,'tc_port_id':port,'tc_port_id':port,'tc_agency_description':description,'xhttp_call':'Y'},
                url: "<?php echo $this->baseurl(); ?>/agency/add",
                success:function(response){
                alert(response);
                    if(response =='null') {
                        error ='Agency name are already exist.';                
                        $( "#agency_name_error" ).html( error );
                        return false;
                    }

                    var result = $.parseJSON(response);
                    alert(result.tc_agency_id); //this alert showing id like '190'
                    alert(result.tc_agency_name); // this alert showing text like 'test'

                    $('#tc_agency_ids').append($('<option></option>').attr('value', "'"+ result.tc_agency_id +"'").text("'"+ result.tc_agency_name +"'"));

                    /* $('#tc_agency_ids').append($('<option>', { // i searched that this commented code is also correct for append the value in multiple select but not working in my code
                        value: result.tc_agency_id,
                        text : result.tc_agency_name 
                    })); */

                    $('#tc_agency_ids option[value='+ result.tc_agency_id +']').attr('selected', true);
                $.fancybox.close();

                },
                error:function (xhr, ajaxOptions, thrownError){
                        alert(thrownError); 
                    }
                });

【问题讨论】:

    标签: ajax jquery-select2


    【解决方案1】:

    您的代码很接近,但有一些变化:

    1. 不要用引号将valuetext 值括起来。
    2. &lt;option&gt; 添加到Select2 控件后,调用.change() 以更新控件。
    3. 最好使用.prop(),而不是.attr() 来设置selected 属性。

    代码:

    var $option = $('<option></option>')
        .attr('value', result.tc_agency_id)
        .text(result.tc_agency_name)
        .prop('selected', true);
    
    $('#tc_agency_ids').append($option).change();
    

    jsfiddle

    注意:我认为您为 .append() 显示的注释代码不正确。你有在哪里看到的链接吗?

    【讨论】:

    • 谢谢,它的工作和这段代码也解决了我在回答中评论的验证问题
    【解决方案2】:

    我通过使用这段代码解决了这个问题, 在警报输入该代码后, 应该使用追加推送代替。

    var data = $('#tc_agency_ids').select2('data');
                        data.push({id:result.tc_agency_id,text:result.tc_agency_name});
                        $('#tc_agency_ids').select2("data", data, true);
    

    谢谢大家

    【讨论】:

    • 我在将数据推送到选择字段后遇到验证问题,jquery 需要验证验证该字段,当我删除验证时,帖子中显示空数据,我认为出现此问题是因为数据未附加到列表中
    • 任何人都有解决这个问题的办法。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-29
    • 1970-01-01
    • 1970-01-01
    • 2020-11-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多