0

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?

Raf Rasenberg
  • 534
  • 2
  • 14
  • 27

2 Answers2

1

When working with <select> in jquery you use $(this).value instead ofthis.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);
        }
    });
Shaphan
  • 1,003
  • 11
  • 10
0

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>
sourav satyam
  • 980
  • 5
  • 11