FB plugin

Source Code Display Plugin

顯示具有 jQuery 標籤的文章。 顯示所有文章
顯示具有 jQuery 標籤的文章。 顯示所有文章

星期四, 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);

星期四, 11月 29, 2018

Bootstrap set select box select value


Method 1. doesn't work for me.

$('#yourSelectBox').val(yourvalue); // not work

Therefore, I try the following code to resolve:

$('#yourSelectBox option').each(function () {
     if (this.value == yourvalue) {
        this.selected = true;
     }
});

熱門文章