Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

People also ask

How do I get the text value of a selected option JavaScript?

function myNewFunction(element) { var text = element. options[element. selectedIndex]. text; // ... }

How do you get the selected value of an element?

To get the value of a select or dropdown in HTML using pure JavaScript, first we get the select tag, in this case by id, and then we get the selected value through the selectedIndex property. The value "en" will be printed on the console (Ctrl + Shift + J to open the console).


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

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

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

var text = getSelectedText('test');

If you use jQuery then you can write the following code:

$("#selectId option:selected").html();

document.getElementById('test').options[document.getElementById('test').selectedIndex].text;

Under HTML5 you are be able to do this:

document.getElementById('test').selectedOptions[0].text

MDN's documentation at https://developer.mozilla.org/en-US/docs/Web/API/HTMLSelectElement/selectedOptions indicates full cross-browser support (as of at least December 2017), including Chrome, Firefox, Edge and mobile browsers, but excluding Internet Explorer.


selectElement.options[selectElement.selectedIndex].text;

References:

  • options collection, selectedIndex property: HTML DOM Select Object
  • text property: HTML DOM Option Object
  • exactly the answer of this question: Option text Property