简体   繁体   中英

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

So I have this code to store the selections of the Select2 widget in my Local Storage:

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

The problem is that this is my HTML generated by Django:

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

So I my local storage I get "7" and "9", but I want this to be the option text, so "The Netherlands" or "France". How can I apply this to my code? I am not very good with JavaScript. I tried these SO posts:

Get selected option text with JavaScript

Retrieving the text of the selected <option> in <select> element

But they use selectIndex, and I am not sure how I can use that in my code.

Can somebody help?

When working with <select> in jquery you use $(this).value instead of this.value to get the content of value attribute.

to get the actual displayed text, use `$(this).text() instead.

refer to this snippet

    $('#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>

So if you need text of option you can simply use $("#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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM