javascript - 检测下拉列表是否为多选

标签 javascript jquery html-select

我有一个通用的下拉列表填充脚本,它使用从各种 jquery 调用返回的选项填充 select。它目前用于单一选择。我需要向它添加填充多选的能力,它按原样工作,但我不想包括初始 * Please choose * 选项。 我正在寻找 jQuery 或纯 Javascript 解决方案。

if (dropdown != null) {
    var regList = document.getElementById(dropdown);
    regList.options.length = 0;
    var opt = document.createElement("option");

    // ** if the dropdown is *not* a multiple="multiple", 
    // add the first option as an empty value

    opt.text = " -- Select --";
    opt.value = "";
    regList.options.add(opt);

    // **

    // loop thorugh child nodes and fill dropdown.
    $.each(arg.d, function () {
        opt = document.createElement("option");
        opt.text = this;
        opt.value = this;
        regList.options.add(opt);
    });
    $('.SpinImage').remove();
}

最佳答案

您可以检查对象的 .multiple 属性

var isMulti = document.getElementById('selectId').multiple; // true/false

jQuery 你可以做 .prop('multiple');

$('#selectId').prop('multiple');

http://jsfiddle.net/31eLyzb3/4/

/*
    Using jQuery, finds and populates the selects on the page.
*/
(function populateAll() {
    /* Here's our options info */
    var opts = {
        'volvo': 'Volvo',
        'saab' : 'Saab',
        'opel' : 'Opel',
        'audi' : 'Audi'
    };
    /*
        This function, given a jQuery select item, and options list, populates it.
        If it is a single-select, it adds a ---Select---/empty value as the first option.
    */
    function populate(listBox, options) {
        var option = null;
        if (listBox.prop('multiple') === false) {
            option = document.createElement('option');
            option.text = '---Select---';
            option.value = '';
            listBox.append(option);
        }
        $.each(options, function (value, label) {
            option = document.createElement('option');
            option.text = label;
            option.value = value;
            listBox.append(option);
        });
    }
    /* Find all select tags on page and populate with 'opts' data */
    $('select').each(function() {
        populate($(this), opts);
    });
})();

关于javascript - 检测下拉列表是否为多选,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33395303/

相关文章:

javascript - 如何将 puppeteer-core 与 Electron 一起使用?

javascript - "for"循环在Javascript中的奇怪使用,请解释

javascript - 如果用户在 jsp 中填写一个字段(同时使用 spring mvc 和 hibernate),我如何自动填写其他表单字段

javascript - 带有两个溢出 :auto; object disappears 的 div 的 jquery sortable()

javascript - 带有覆盖 anchor 的模态

jquery - 如何在用户要选择选项后扩展 'select' 选项宽度

javascript - 将 Doc 属性作为参数传递给 Mongodb 上的函数

javascript - 将原始字符串从 api 转换为货币格式

jquery - 使用 jQuery 在 IE 中隐藏选择选项

android - HTML 选择下拉菜单在 android webview 中不起作用