繁体   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