簡體   English   中英

使用 Select2 小部件時檢索選項名稱而不是本地存儲 JavaScript 中的值

[英]Retrieve the option name instead of the value in Local Storage JavaScript when using Select2 widget

所以我有這個代碼來在我的本地存儲中存儲 Select2 小部件的選擇:

// watch for changes to locations select
$('#locations').change(function() {
    var selected = []; // create an array to hold all currently selected locations

    // loop through each available location
    $('#locations option').each(function() {
        // if it's selected, add it to the array above
        if (this.selected) {
            selected.push(this.value);
        }
    });

    // store the array of selected options
    localStorage.setItem('locations', JSON.stringify(selected));
});

問題是這是我的 Django 生成的 HTML:

<select name="preferred_location_test" id="locations" multiple="">
  <option value="7">The Netherlands</option>
  <option value="9">France</option>
</select>

所以我的本地存儲我得到“7”和“9”,但我希望這是選項文本,所以“荷蘭”或“法國”。 如何將其應用於我的代碼? 我不太擅長 JavaScript。 我試過這些SO帖子:

使用 JavaScript 獲取選定的選項文本

在 <select> 元素中檢索所選 <option> 的文本

但是他們使用 selectIndex,我不確定如何在我的代碼中使用它。

有人可以幫忙嗎?

在 jquery 中使用<select> ,您使用$(this).value而不是this.value來獲取value屬性的內容。

要獲得實際顯示的文本,請改用`$(this).text()。

參考這個片段

    $('#locations option').each(function() {
        // if it's selected, add it to the array above
        if (this.selected) {
            var location = $(this).text();
            selected.push(location);
        }
    });

 let selected_values = []; $("#locations").on('change', function() { $('#locations :selected').each(function(i, selected) { selected_values[i] = $(selected).text(); }); alert(selected_values); });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <select name="preferred_location_test" id="locations" multiple=""> <option value="7">The Netherlands</option> <option value="9">France</option> </select>

因此,如果您需要選項文本,您可以簡單地使用$("#test option:selected").html()

 $("#test").on('change', function() { if ($(this).val() == '1') { alert($("#test option:selected").html()); } })
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <select id="test"> <option value="1">Test</option> <option value="2">1Test</option> </select>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM