6

看看下面的选择:

<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. 因此,如果选择了 4,我希望选择显示 B - 4

4

3 回答 3

10

如果您需要将所选值恢复为原始值...试试这个... 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]);

    });

});

使用 select2 插件更新您可以执行以下操作 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; }
});
于 2013-09-26T20:19:17.347 回答
1

更新所选值很麻烦,但请查看此演示

哈奇演示

$('#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);
    }
});
于 2013-09-26T19:51:00.140 回答
0

尝试这个:

jsFiddle在这里

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

});
于 2013-09-26T19:57:02.203 回答