Javascript 检测下拉列表是否为多选列表
我有一个通用的下拉列表填充脚本,它用各种jquery调用返回的选项填充Javascript 检测下拉列表是否为多选列表,javascript,jquery,html-select,Javascript,Jquery,Html Select,我有一个通用的下拉列表填充脚本,它用各种jquery调用返回的选项填充select。目前,它只适用于单一选择。我需要添加到它的能力,以填补一个多重选择,这是工作的原样,但我不想包括最初的*请选择*选项。 我正在寻找jQuery或纯Javascript解决方案 if (dropdown != null) { var regList = document.getElementById(dropdown); regList.options.length = 0; var opt
select
。目前,它只适用于单一选择。我需要添加到它的能力,以填补一个多重选择,这是工作的原样,但我不想包括最初的*请选择*选项。
我正在寻找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();
}
您是否使用插件或库来呈现下拉列表?该库支持修改或删除他们所称的。在您的情况下,“请选择”字符串。您可以通过以下方式检查是否存在
多个属性,如果存在,则其值不为真:
if(!regList.hasAttribute("multiple") && !regList.getAttribute("multiple")) {
opt.text = " -- Select --";
opt.value = "";
regList.options.add(opt);
}
可以检查对象的.multiple属性
var isMulti = document.getElementById('selectId').multiple; // true/false
jQuery-youcando.prop('multiple')
$('#selectId').prop('multiple');
/*
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);
});
})();