Simon Delaunay
Simon Delaunay

Reputation: 145

JavaScript selectedIndex text on multiple choice

I have a list of tag in my input using Symfony Twig templating like that :

    <select id="choices-multiple-remove-button" class="form-control" name="choices-multiple-remove-button"  placeholder="Compétences" multiple>
    {% for skill in skills %}
      <option value="{{skill.id}}">{{skill.label}}</option>
      {% endfor %}
    </select>
  </div>

Here in JS i can get all values selected with "elements[i].value" :

function hello() {
  var elements = document.getElementById('choices-multiple-remove-button');
  for(var i=0; i < elements.length; i++) {
    console.log(elements[i].value);
    console.log(elements[i].options[elements[i].selectedIndex].text);
    // Throw Error //
  }
}
document.getElementById("workingbutton").addEventListener("click", hello);

Here :

console.log(elements[i].options[elements[i].selectedIndex].text);

Cannot read property 'undefined' of undefined at HTMLButtonElement.hello.. How can i do this please ? What's wrong ?

Upvotes: 1

Views: 275

Answers (1)

Pranav C Balan
Pranav C Balan

Reputation: 115232

Filter the selected options and then get its text content. In order to do that convert options property into an array, then use Array#filter method to filter selected options and finally use Array#map to extract text values from selected options into an array.

var element = document.getElementById('choices-multiple-remove-button');
console.log([...element.options].filter(ele => ele.selected).map(ele => ele.text));
<select id="choices-multiple-remove-button" class="form-control" name="choices-multiple-remove-button" placeholder="Compétences" multiple>
  <option value="1" selected>1</option>
  <option value="2" selected>2</option>
</select>

Upvotes: 1

Related Questions