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
If you want to get selected option value, you can use $(select element). val() .
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.
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.
The <optgroup> HTML element creates a grouping of options within a <select> element.
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; }
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With