Mr. Tomar
Mr. Tomar

Reputation: 365

Append option in multiple select

I want to append option in multiple select, option value come from ajax responce I using jquery-select2 for multiple select feild My script code

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

Upvotes: 0

Views: 4370

Answers (2)

John S
John S

Reputation: 21482

Your code is close, but a few changes:

  1. Do not surround the value and text values with quotes.
  2. After adding an <option> to a Select2 control, call .change() to get the control to update.
  3. It might be better to use .prop(), rather than .attr() to set the selected property.

Code:

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

Note: I don't think the commented code you show for .append() is correct. Do you have a link for where you saw that?

Upvotes: 1

Mr. Tomar
Mr. Tomar

Reputation: 365

I solved that by using this code, After alert put that code, In-place of append push should be used.

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

thanks for all

Upvotes: 1

Related Questions