Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to show the optgroup value + option value as the selection

Take a look at the following select:

<select>
<optgroup label="A">
<option value="">1</option>
<option value="">2</option>
<option value="">3</option>
<optgroup label="B">
<option value="">4</option>
<option value="">5</option>
<option value="">6</option>
</select>

When any element is selected I would like to display its label + value in the selection instead of just value. So if 4 is selected I would like the selection to show B - 4

like image 360
user1029829 Avatar asked Sep 26 '13 19:09

user1029829


People also ask

How do you get the selected option value?

If you want to get selected option value, you can use $(select element). val() .

What is the purpose of the Optgroup element in a select list?

The <optgroup> tag is used to group related options in a <select> element (drop-down list). If you have a long list of options, groups of related options are easier to handle for a user.

Can you style Optgroup?

A style attribute on an <optgroup> tag assigns a unique style to the option group. Its value is CSS that defines the appearance of the option group.

Which element allows for the creation of groups of options in a select menu?

The <optgroup> HTML element creates a grouping of options within a <select> element.


1 Answers

if you need the selected value back to its original value... try this... http://jsfiddle.net/kasperfish/sxvW2/2/

$('select').change(function () {
    var opt = $(this).find(':selected');
    var sel = opt.text();
    var og = opt.closest('optgroup').attr('label');
    //alert(sel);
    //alert(og);

    $(this).blur().find(':selected').text(sel + '-' + og);

});

$('select').focus(function () {
    $(this).find('option').each(function(){
        console.log($(this).text());
        t=$(this).text().split('-');
        $(this).text(t[0]);

    });

});

UPDATE using the select2 plugin you can do the following http://jsfiddle.net/kasperfish/bJxFR/4/

function format(item) {
       opt = $('select').find(':selected');
       sel = opt.text();
       og = opt.closest('optgroup').attr('label');
      return item.text+'-'+og;

}
$("select").select2({
formatSelection: format,
escapeMarkup: function(m) { return m; }
});
like image 158
kasper Taeymans Avatar answered Nov 15 '22 00:11

kasper Taeymans