从选择框中动态删除在其他选择框中选择的选项
Deleting dynamically options from select box that were selected in other select box,
我有两个select box
Jquery Mobile
使用相同的数据 - 选项。 在初始化页面开始时,我动态构建它们:
var first = document.getElementById("selectBoxFirst");
var second = document.getElementById("selectBoxSecond");
for (var i = 0; i < this.data.length; i++)
{
first.options[i] = new Option(this.data[i].option, this.data[i].optionId);
second.options[i] = new Option(this.data[i].option, this.data[i].optionID);
}
我尝试做下一件事:当用户在一个选择框中选择一个选项时,此选项将在第二个选项中删除......如果您再次选择其他选项,则最后一个选项将从第二个选项中删除,并显示上一个选项,依此类推...
任何想法如何实现它?
您可以选择隐藏或禁用所选选项。
-
隐藏所选选项:(这可能不适用于旧浏览器)
-
.CSS:
.hide { display: none; }
-
.JS
$('#first').on('change', function () { $('select option.hide').removeClass('hide'); var sel = $('option:selected', this).index(); $('#second option:eq("' + sel + '")').addClass('hide'); }); $('#second').on('change', function () { $('select option.hide').removeClass('hide'); var sel = $('option:selected', this).index(); $('#first option:eq("' + sel + '")').addClass('hide'); });
-
演示
-
禁用所选选项: (这不适用于 IE7 和更早版本)
-
.JS
$('#first').on('change', function () { $('select option:disabled').prop('disabled', false); var sel = $('option:selected', this).index(); $('#second option:eq("' + sel + '")').prop('disabled', true); }); $('#second').on('change', function () { $('select option:disabled').prop('disabled', false); var sel = $('option:selected', this).index(); $('#first option:eq("' + sel + '")').prop('disabled', true); });
-
演示
使用普通的JavaScript,该方法相当简单:
var select1 = document.getElementById('first'),
select2 = document.getElementById('second');
select1.addEventListener('change', function() {
while (select2.firstChild) {
select2.removeChild(select2.firstChild);
}
for (var i = 0, len = this.options.length; i < len; i++) {
if (this.options[i].value !== this.value) {
select2.appendChild(this.options[i].cloneNode());
}
}
}, false);
演示:http://jsfiddle.net/Tp2z7/
你可以用jQuery写同样的东西,稍微短一点:
$('#first').on('change', function() {
$('option:not(:selected)', this).clone().appendTo($('#second').empty());
});
演示:http://jsfiddle.net/Tp2z7/1/
相关文章:
- CKeditor:更改对话框中的默认选择选项
- 如何在从多选下拉列表中选择选项值时动态生成文本框
- AngularJs列表ng单击以选择选项转换
- 使用基于文本的 Jquery 选择选项
- 当选择值x时,Javascript需要在正确的位置显示文本区域,从而循环通过具有选择选项的表单
- 在php和mysql中选择选项.一旦选择了选项,就列出我的sql数据库数据
- 选择选项时如何显示警报
- 使用php动态更改选择选项
- 选择“选择选项”时显示文本.怎么做
- LEAFLET地图和带有选择选项的标记-ANGULARjs
- 使用js将动态内容添加到选择选项列表中
- 用于使用javascript循环选择选项
- AngularJS-选择选项并在函数中使用它
- 禁用/启用基于单选/选择选项所选Javascript的文本框
- 如何使用jQuery隐藏与选择选项相关的选择选项列表
- 选择选项是添加或删除事件
- 使用jQuery向“选择选项”添加默认属性
- 构建HTML选择字段并使用JavaScript数组选择选项
- 带有动态选择选项的Firefox html5验证异常
- 只有当Angular从资源对象检索数据时,才选择选项元素