Get the optgroup label and option value and show it in a div with Jquery

3

I have the following code:

<select>
    <optgroup label="fruta">      
        <option value="banana">banana</option>
        <option value="uva">uva</option>
    </optgroup>

    <optgroup label="legume">
        <option value="batata">batata</option>
        <option value="cenoura">cenoura</option>
    </optgroup>
</select>
<div id="label_value"></div>

I would like in JQuery to get the value of the label and value and play on a div.

    
asked by anonymous 08.07.2015 / 13:11

2 answers

1

You can do it like this:

$('select').change(function () {
    var label = $(this).find(':selected').closest('optgroup').attr('label');
    $('#label_value').html(label);
});

jsFiddle: link

The code will fetch the option selected and then go up in the DOM to fetch optgroup from that option . It reads the label attribute.

    
08.07.2015 / 13:17
0

Sergio, thank you very much. I am now learning to do JS and I am inventing certain situations and practicing. I even wanted to see not only the "label" attribute, but with it it would appear the "value" attribute of the option. Then I made the following changes

$(window).load(function(){
  $('select').change(function () {
    var label = $(this).find(':selected').closest('optgroup').attr('label');
    var value = $(this).find(':selected').closest('option').attr('value');
    $('#label_value').html(label+value);
});
});
    
08.07.2015 / 14:45