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

Asked

Viewed 578 times

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 take the value of the label and value and play in a div.

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: http://jsfiddle.net/cujweb2h/

The code retrieves the option selected and then goes up in the DOM to get the optgroup of that option. There reads the attribute label.

  • Hello Sergio, is it possible to write the first options in the div? Like: In html the first option is banana fruit. You can already show up before the user chooses something else?

  • @Schoolgirl, yes, just do it $('select').change(); -> http://jsfiddle.net/cujweb2h/1/

  • 1

    Once again, thank you.

0

Sergio, thank you very much. I am learning now to do JS and I am inventing certain situations and practice. I even wanted not only the "label" attribute to appear, but the option "value" attribute to appear next to it. 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);
});
});
  • I saw now that you gave this answer as well. I think this is a continuation of the question, not a right answer? If this is the case you should delete. But as for what you’re referring to, you can use the this.value within that function to have the option chosen. Thus: http://jsfiddle.net/cujweb2h/2/

  • 1

    Nothing. It was just to thank and show a small change I made and can not put code in the comments. But thanks for the tip. I’m new to the forum, I still have a lot to learn.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.