Get value of option selected in a child element (jquery / javascript)

1

I have the following scenario:

a series of SELECT elements in a series of DIV with the same class.

<div class="elementLine">
persona 1
  <select id="coches">
    <option value='si' selected>si</option>
    <option value='no'>no</option>
  </select>
  <select id="motos">
    <option value='si'>si</option>
    <option value='no' selected>no</option>
  </select>
</div>
<div class="elementLine">
persona 2...

I need to access the value of each OPTION: SELECTED, iterating through each line of the with the .each function; The problem is that I can not get the SELECT value. Does anyone know how to access that particular item?

$( ".elementLine" ).each(function(index, value){ 
    var tieneCoche= $(this).children( $("#coches").children("option:selected") ).val()  ;  
    console.log( "coche value:"+tieneCoche);
});
    
asked by JorgeJob 12.09.2018 в 16:59
source

1 answer

0

It's much simpler than you think, you should take each select in a each() to then get the value of said select with the function val() from jQuery.

// cuando esté listo el DOM
$(document).ready(function() {
  // selecciono los select y los recorro en un each
  $('.elementLine select').each(function(index) {
    // obtengo el valor del select
    var value = $(this).val();
    
    console.log(value);
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="elementLine">
persona 1
  <select id="coches">
    <option value='si' selected>si</option>
    <option value='no'>no</option>
  </select>
  <select id="motos">
    <option value='si'>si</option>
    <option value='no' selected>no</option>
  </select>
</div>
    
answered by 12.09.2018 / 17:05
source