Get selected option within an optgroup

1

Having a select like this:

<select id="main">
   <optgroup label="Coches">
      <option value="Mustang">Mustang</option>
      <option value="Ford">Ford</option>
   </optgroup>
   <optgroup label="Motos">
      <option value="Scooter">Scooter</option>
      <option value="Extra">Extra</option>
   </optgroup>
</select>

I'm looking for a way to get the value of the option selected by the user through JavaScript, after many tests and information search I do not give the right one. As far as I know, you have to treat the optgroup as an object, and using an index you can get the selected option, right?

Greetings and thanks

    
asked by Vicinflames 20.03.2018 в 13:06
source

2 answers

3

If what you want is the value of the option selected by JavasScript, it looks like this:

var select = document.getElementById('main');
select.addEventListener('change',
function(){
var selectedOption = this.options[select.selectedIndex];
console.log(selectedOption.value + ': ' + selectedOption.text);
});

And for JQuery:

 $(document).ready(function(){
    $('#main').change(function () {            
       $("#main option:selected").each(function () {
            elegido=$(this).val();                                  
       });         
    });
});   

or

$('#main').val()
    
answered by 20.03.2018 / 13:30
source
0

With JQuery you can do it this way:

EDIT

Added code to get the label of optgroup as well.

$(document).ready(function(){
  $("#main").on("change",function(){
    console.log($(this).val());
    console.log($(this.options[this.selectedIndex]).closest('optgroup').attr('label'));
  })
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<select id="main">
  <option value="">Seleccione una opción</option>
  <optgroup label="Coches">
   <option value="Mustang">Mustang</option>
   <option value="Ford">Ford</option>
  </optgroup>
  <optgroup label="Motos">
   <option value="Scooter">Scooter</option>
   <option value="Extra">Extra</option>
  </optgroup>
</select>
    
answered by 20.03.2018 в 13:27