Get the selected select value - Javascript - DOM

2

I want to get the value (.value) or text (.text) of the chosen option from a drop-down list of a select in a form.

How do I access the text of the selected selection?

HTML code of the select element:

<select name="provincia" id="provincia">

Javascript code:

//Guardamos en una variable el nombre del campo provincia.
var idprovincia = document.getElementById("idprovincia");
var pro = idprovincia.options[idprovincia.selectedIndex].value;
//Creamos un nodo de texto que agregaremos al div.
var pro_valor = document.createTextNode("Provincia: "+pro);
//Añadimos el nuevo nodo al final de la lista.
div.appendChild(pro_valor);
    
asked by omaza1990 22.05.2017 в 21:23
source

3 answers

8

With the text property of the selected option.

In your code you are accessing the value of the selected option through the value property. In the same way, through the text property you can access the text of the option:

var select = document.getElementById('provincia');
select.addEventListener('change',
  function(){
    var selectedOption = this.options[select.selectedIndex];
    console.log(selectedOption.value + ': ' + selectedOption.text);
  });
<select name="provincia" id="provincia">
  <option value="" disabled selected>Seleccione una Provincia...</option>
	<option value="AB">Albacete</option>
	<option value="AL">Almería</option>
	<option value="AR">Araba</option>
	<option value="AV">Ávila</option>
	<option value="BA">Badajoz</option>
</select>
    
answered by 22.05.2017 в 21:34
2

Just as you have it works well if you did not make a mistake when copying it, there is a typo in var idprovincia = document.getElementById("idprovincia"); id id would be var idprovincia = document.getElementById("provincia");

    
answered by 22.05.2017 в 21:39
0

window.onload = function() {
  imprimirValor();
}

function imprimirValor(){
  var select = document.getElementById("feedingHay");
  var options=document.getElementsByTagName("option");
  console.log(select.value);
  console.log(options[select.value-1].innerHTML)
}
<form action="feeding" method="post">
    <select id="feedingHay" onChange="imprimirValor()">
       <option value="1">Hola</option>
       <option value="2">Como</option>
       <option value="3">Estas</option>
       <option value="4">Amigo</option>
       <option value="5">!</option>
   </select>

 
</form>
    
answered by 22.05.2017 в 21:32