How can I know the value of an option within an input type select in HTML?

-1

If I have this code. How can I know with JQuery or with DOM the value of, for example, the option of value 2?

 <select class="select" id="mySelect">
      <option value="0">>HOLA</option>
      <option value="1">>HOLA2</option>
      <option value="2">>HOL3</option>
      <option value="3">>HOLA4</option>
    </select/>
    
asked by Alfonso Rodríguez 08.11.2017 в 09:49
source

2 answers

4

you just have to use:

$( "#mySelect" ).val();

If you want to get the list of values you can use

$("#mySelect").each(function()
{
   $(this).val(); //te retornara el valor
   $(this).text(); // te dará el texto
});
    
answered by 08.11.2017 / 09:51
source
1

window.addEventListener("DOMContentLoaded", () => {
let options = document.getElementById("mySelect").
getElementsByTagName("option");
var onemore = 1;
Array.from(options).forEach(e =>{
console.log('Soy la opción número ${onemore} y tengo de texto:
${e.innerHTML}
');
onemore++;
});
});
<html>
 <body>
 <select class="select" id="mySelect">
      <option value="0">HOLA</option>
      <option value="1">HOLA2</option>
      <option value="2">HOL3</option>
      <option value="3">HOLA4</option>
</select>
</body>
</html>
    
answered by 08.11.2017 в 10:07