I have a Jquery script where I am doing an ajax call and the value that I get in return I am using it to add it in the select option , Drop down menu ,
My Problem is that its not showing as selected ,
The JS is as follows
(function($, window) {
$.fn.replaceOptions = function(options) {
var self, $option;
this.empty();
self = this;
$.each(options, function(index, option){
$option = $("<option></option>")
.attr("value", option.value)
.text(option.text);
self.append($option);
});
this.prop('disabled', false);
};
})(jQuery, window);
$(document).on('click', ".add1", function () {
var val1 = $(".selectLevel", $(this).parents("tr")).eq(0).val(),
val2 = $(".selectLevel", $(this).parents("tr")).eq(1).val(),
url = "http://www.xxxyz.com/xxx/xxx/web/ajax.php",
val3 = $(this).closest('tr').find('input').val(),
closeSelect = $(this).closest('td').find('select');
if (val3 == '' || val3 == null) alert('You need to add value in the input box');
else {
var posting = $.post(url, {
im_core: 'selectAjaxUpdate',
geo_level1: val1,
geo_level2: val2,
geo_level3: val3,
pais: <? php echo $_POST['pais'] ?>
}).done(function (data) {
var obj = $.parseJSON(data);
$.each(obj, function (key, value) {
myArray.push({
text: obj[key].value,
value: obj[key].id
});
});
//$(closeSelect).html('myArray');
$(closeSelect).replaceOptions(myArray);
});
}
});
Can any one help me , With this
Thanks in Advance
The problem in
$(closeSelect).replaceOptions(myArray);
try change to
closeSelect.replaceOptions(myArray);
And if you use replaceoptions method from here , it not support setting selected value,because it only take array of objects and appent them to select
You are changing source of dropdown but you are not setting new value once you source gets change. You just need to set selected vaulue.
$(document).on('click', ".add1", function () {
var val1 = $(".selectLevel", $(this).parents("tr")).eq(0).val(),
val2 = $(".selectLevel", $(this).parents("tr")).eq(1).val(),
url = "http://www.xxxyz.com/xxx/xxx/web/ajax.php",
val3 = $(this).closest('tr').find('input').val(),
closeSelect = $(this).closest('td').find('select');
if (val3 == '' || val3 == null) alert('You need to add value in the input box');
else {
var posting = $.post(url, {
im_core: 'selectAjaxUpdate',
geo_level1: val1,
geo_level2: val2,
geo_level3: val3,
pais: <? php echo $_POST['pais'] ?>
}).done(function (data) {
var obj = $.parseJSON(data);
$.each(obj, function (key, value) {
myArray.push({
text: obj[key].value,
value: obj[key].id
});
});
//$(closeSelect).html('myArray');
$(closeSelect).replaceOptions(myArray);
//Set selectedValue over here
$(closeSelect).val(yourSelectedValue);
});
}
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.