在多个选择中附加选项

时间:2014-12-24 12:09:04

标签: ajax jquery-select2

我想在多个select中追加选项,选项值来自ajax响应,使用jquery-select2进行多个select字段 按脚本代码

$.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); 
                    }
                });

2 个答案:

答案 0 :(得分:1)

我通过使用此代码解决了这个问题, 警报后把那段代码, 应该使用附加推送的原位。

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);

感谢所有

答案 1 :(得分:0)

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

  1. 请勿使用引号括起valuetext值。
  2. <option>添加到Select2控件后,调用.change()以使控件更新。
  3. 最好使用.prop()而不是.attr()来设置selected属性。
  4. 代码:

    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()显示的注释代码不正确。你有看到它的链接吗?