javascript – How to get the text of option and then extract a number?

Question:

I have the following <select> , what I want to do is grab/get the text it contains and, if possible, the numerical value.

   <select name="select" id="comprar-js">
            <option value="show1">PLATEA (450$)</option>
            <option value="show2">CAMPO (800$)</option>
            <option value="show3">ESCENARIO (1000$)</option>
            <option value="shoW4">BANDEJA (3000$)</option>
        </select>

I want to access the text that each <option> contains (PLATEA (450$)) and once I get it, use the number value it has to perform operations.

Answer:

You can do it with the following line

document.getElementById('comprar-js').options[document.getElementById('comprar-js').selectedIndex].text;

document.getElementById('comprar-js').options returns the array of options and document.getElementById('comprar-js').selectedIndex returns the selected index of the array.

I recommend that you use the data- attributes to facilitate access to extra information. For example

<select name="select" id="comprar-js">
            <option data-valor="450" value="show1">PLATEA (450$)</option>
            <option data-valor="800" value="sho2">CAMPO (800$)</option>
            <option data-valor="1000" value="show3">ESCENARIO (1000$)</option>
            <option data-valor="3000" value="shoW4">BANDEJA (3000$)</option>
</select>

And modifying the previous code we can access the value with:

let valorEntrada =  document.getElementById('comprar-js').options[document.getElementById('comprar-js').selectedIndex].dataset.valor;

Here you can find more information about data attributes https://developer.mozilla.org/es/docs/Learn/HTML/como/Usando_atributos_de_datos

Scroll to Top