有人可以帮我在jQuery中处理这个问题
我有一个要求,我有两个下拉列表:
我需要从第二个下拉列表中删除所有无效选项。我如何实现这一目标?
例如: 如果用户选择 numberOfFloors 选项为3,那么我应该从 whichFloorYouStay 下拉列表中删除选项4和5,然后只需将1,2,3加载为 whichFloorYouStay 选项。
同样,如果用户选择 numberOfFloors 选项为1,那么我应该从 whichFloorYouStay 下拉列表中删除选项2,3,4,5,只需将1加载为< strong> whichFloorYouStay 选项。
请找到我的JSBin链接:
http://jsbin.com/sibufive/1/edit?html,js,output
答案 0 :(得分:0)
var value = $("#numberOfFloors").val();
应该成为
var value = $("#numberOfFloors").val();
value-=1
我还建议在第一组选项中添加一个值0
,以便您永远不会让用户从1
开始并尝试转到第二个菜单
答案 1 :(得分:0)
试试这个:
$(document).ready(function () {
//NEW CODE:
var floorsvals = new Array();
var lastvalue = Number.MAX_VALUE; //Useful for checking whether we need to append or remove elements - Initialize this with an arbitrarily large number
//Fill possible floor vals with value of <option>'s
$("#numberOfFloors option").each(function () {
floorsvals.push($(this).val());
});
//NOTE: If you already know the values of the numberOfFloors array, you can just add those values straight into the "floorsvals" array
//The above loop is just handy if you are dynamically generating a <select> list and don't already know the values
$("#numberOfFloors").change(function () {
alert($("#numberOfFloors").val());
var value = $("#numberOfFloors").val();
//NEW CODE:
//If we need to append...
if (value > lastvalue) { //This value is larger than the last value we just had
for (i = 0; i < floorsvals.length; i++) {
if (floorsvals[i] <= value && $('#whichFloorYouStay option[value=' + floorsvals[i] + ']').length === 0) { //Floor value is less than the selected maxvalue and an option with this floor value doesn't already exist...
$('<option value="' + floorsvals[i] + '">' + floorsvals[i] + '</option>').appendTo("#whichFloorYouStay"); //...So add that floor value
}
}
} else { //Otherwise, we need to remove
//OLD CODE:
$('#whichFloorYouStay option').each(function () { //Go through each option
if ($(this).val() > value) { //If this option's value is greater than the numberOfFloors value, remove it
$(this).remove();
}
});
}
//NEW CODE:
lastvalue = value; //Update last value chosen with this value
});
});