Reputation: 365
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
Reputation: 21482
Your code is close, but a few changes:
value
and text
values with quotes.<option>
to a Select2 control, call .change()
to get the control to update. .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();
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
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