我有一个简单的 HTML 选择表单,其中包含一些项目。我正在使用 javascript 来限制用户可以选择的项目数量。
在 HTML 中,我有以下代码:
<select name="category" multiple id="category" onchange="checkMaxSelected(this, 3, 'Max number of categories you can select: ');">
<option value="orange">orange</option>
<option value="apple">apple</option>
<option value="banana">banana</option>
<option value="pear">pear</option>
<option value="strawberry">strawberry</option>
</select>
我将三个变量传递给 javascript 函数 checkMaxSelected:
- 哪个选择表格(即这个)
- 用户可以在表单中执行的最大选择数(在我的情况下为 3)
- 应在警告框中显示的错误消息。
JS代码如下:
function checkMaxSelected (select, maxSelected, displ_error_nummaxcat) {
if (!select.storeSelections) {
select.storeSelections = new Array(select.options.length);
select.selectedOptions = 0;
}
for (var i = 0; i < select.options.length; i++) {
console.log('select.options[i].selected: '+select.options[i].selected+' select.storeSelections[i]: '+select.storeSelections[i]);
if (select.options[i].selected &&
!select.storeSelections[i]) {
if (select.selectedOptions < maxSelected) {
select.storeSelections[i] = true;
select.selectedOptions++;
}
else {
alert(displ_error_nummaxcat + maxSelected);
console.log('HERE I SHOW ALERT!');
select.options[i].selected = false;
}
}
else if (!select.options[i].selected &&
select.storeSelections[i]) {
select.storeSelections[i] = false;
select.selectedOptions--;
}
}
};
此解决方案在 Firefox、Safari 和 IE 下完美运行,但不适用于 Chrome。为什么?
任何帮助是极大的赞赏。先感谢您。
额外信息:
我一直在尝试使用 firebug 为 firefox 和 Chrome 调试它,但徒劳无功:使用 Firefox 当我选择选择表单的第一项时,我看到了 firebug 控制台:
select.options[i].selected: true select.storeSelections[i]: undefined
select.options[i].selected: false select.storeSelections[i]: undefined
select.options[i].selected: false select.storeSelections[i]: undefined
select.options[i].selected: false select.storeSelections[i]: undefined
select.options[i].selected: false select.storeSelections[i]: undefined
(哪个是对的)。
与 Chrome 相同的操作(即选择第一项)会直接触发错误消息。这是 Chrome 中的 firebug 控制台输出:
select.options[i].selected: true select.storeSelections[i]: undefined
HERE I SHOW ALERT!
select.options[i].selected: false
select.options[i].selected: false select.storeSelections[i]: undefined
select.options[i].selected: false select.storeSelections[i]: undefined
select.options[i].selected: false select.storeSelections[i]: undefined
select.options[i].selected: false select.storeSelections[i]: undefined