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

Viewed 356041

In the following:

<select id="test">
    <option value="1">Test One</option>
    <option value="2">Test Two</option>
</select>

How can I get the text of the selected option (i.e. "Test One" or "Test Two") using JavaScript

document.getElementsById('test').selectedValue returns 1 or 2, what property returns the text of the selected option?

14 Answers
function getSelectedText(elementId) {
    var elt = document.getElementById(elementId);

    if (elt.selectedIndex == -1)
        return null;

    return elt.options[elt.selectedIndex].text;
}

var text = getSelectedText('test');

The options property contains all the <options> - from there you can look at .text

document.getElementById('test').options[0].text == 'Text One'

The :checked selector can be used with document.querySelector to retrieve the selected option.

let selectedText = document.querySelector('#selectId option:checked').text;
// or
let selectedText = document.querySelector('#selectId')
      .querySelector('option:checked').text;

document.querySelector('button').addEventListener('click', function(e) {
  console.log(document.querySelector('#selectId option:checked').text);
});
<select id="selectId">
  <option>a</option>
  <option>b</option>
  <option>c</option>
</select>
<button>
Get selected text
</button>

For select elements with the multiple attribute, document.querySelectorAll can be used to obtain all selected options.

let selectedText = [...document.querySelectorAll('#selectId option:checked')]
   .map(o => o.text);

document.querySelector('button').addEventListener('click', function(e) {
  let selectedText = [...document.querySelectorAll('#selectId option:checked')]
                      .map(o => o.text);
  console.log(selectedText);
});
<select id="selectId" multiple>
  <option>a</option>
  <option>b</option>
  <option>c</option>
</select>
<button>
Get selected text
</button>

Easy, simple way:

const select = document.getElementById('selectID');
const selectedOption = [...select.options].find(option => option.selected).text;

It is pretty simple. In javascript anything with an ID doesn't need document.queryselector or $('#test') you can just use test. Then you simply loop over the selectedOptions which is apart of javascript and you can add it to a new array and use that data how ever you want.

let selectedItems = [];
for ( var i = 0; i < test.selectedOptions.length; i++) {
    selectedItems.push(test.selectedOptions[i].text);
}

Also

// if you want values
selectedItems.push(test.selectedOptions[i].value);
Related