我該怎麼「正確」地將資料丟到 select 給使用者選?
以及下次讀使用者的資料,選中的那個自動 selected
我想到如果是普通 input 欄位就 $('#xxx').val(val) 把直丟進去就可以了(?
有比較正確的做法嗎?
或是相關教學
$('#select1').append(`<option value="${optionValue}">${optionText}</option>`); // 作法二 使用new Option() $('#select1').append(new Option(optionText, optionValue)); // 作法三 利用val()和text() $('#select1').append($('<option>').val(optionValue).text(optionText));

  • 讓option為selected
    參考 stackoverflow:Setting the selected attribute on a select list using jQuery
    // 使用attr()
        $("select option[value='xxx']").attr("selected","selected");
    
  •