FB plugin

Source Code Display Plugin

星期四, 2月 21, 2019

[bug] jquery select change default value not working


My env is JQuery 3.3.1 / Bootstrap 4.0.0 / Laravel 5.7


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

This will WORK when getting the data in the FIRST TIME.
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);

沒有留言:

熱門文章