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

醉酒当歌 提交于 2019-12-13 13:07:16

问题


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


回答1:


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; }
});



回答2:


Its hacky to update the selected value but check out this demo

Hacky Demo

$('#select').change(function () {
    var selectedOption = $('#select option:selected');
    var label = selectedOption.closest('optgroup').attr('label');
    var selectText = selectedOption.text();

    var length = $(this).find(':selected').text().length;

    if (length < 2) {
        $(this).find(':selected').text(label + ' - ' + selectText);
    }
});



回答3:


Try this:

jsFiddle here

HTML:

<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>

jQuery/javascript:

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

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

});


来源:https://stackoverflow.com/questions/19037232/how-to-show-the-optgroup-value-option-value-as-the-selection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!