I want to change the select default value after retrieving data through AJAX. The following code is the original version
$("#mySelect option").each(function(){
if($(this).val() == myArray[0].id) {
$(this).attr('selected', true);
} else {
$(this).attr('selected', false);
}
});
if($(this).val() == myArray[0].id) {
$(this).attr('selected', true);
} else {
$(this).attr('selected', false);
}
});
BUT, if I keep getting other selection, the selected appears wrong result. The text show the wrong default text.
Therefore, my workaround method is to remove the option and append new option code. Here is the example:
var optionHtml = "<option value=\"0\">My default text</option>";
for (i = 0; i < myOptionArr.length; i++) {
if (mySelectedOption == myOptionArr[0].id) {
optionHtml += "<option value=\"" + myOptionArr[i].id + "\" selected " + " >" + myOptionArr[i].desc + "</option>";
} else {
optionHtml += "<option value=\"" + myOptionArr[i].id + "\">" + myOptionArr[i].desc + "</option>";
}
}
$("#inctypeSel2").append(optionHtml);
for (i = 0; i < myOptionArr.length; i++) {
if (mySelectedOption == myOptionArr[0].id) {
optionHtml += "<option value=\"" + myOptionArr[i].id + "\" selected " + " >" + myOptionArr[i].desc + "</option>";
} else {
optionHtml += "<option value=\"" + myOptionArr[i].id + "\">" + myOptionArr[i].desc + "</option>";
}
}
$("#inctypeSel2").append(optionHtml);
沒有留言:
張貼留言