根据另一个下拉列表中的选择填充一个下拉列表我需要改变下拉B的内容,根据下拉A中的选择使用javascript。不涉及db查询-我事先知道在A中应该选择B的内容,我已经找到了一些使用Ajax的例子,但是由于不涉及db查询,所以没有必要。有人能为我指出一些示例代码来说明如何做到这一点吗?
3 回答

达令说
TA贡献1821条经验 获得超6个赞
function configureDropDownLists(ddl1, ddl2) { var colours = ['Black', 'White', 'Blue']; var shapes = ['Square', 'Circle', 'Triangle']; var names = ['John', 'David', 'Sarah']; switch (ddl1.value) { case 'Colours': ddl2.options.length = 0; for (i = 0; i < colours.length; i++) { createOption(ddl2, colours[i], colours[i]); } break; case 'Shapes': ddl2.options.length = 0; for (i = 0; i < shapes.length; i++) { createOption(ddl2, shapes[i], shapes[i]); } break; case 'Names': ddl2.options.length = 0; for (i = 0; i < names.length; i++) { createOption(ddl2, names[i], names[i]); } break; default: ddl2.options.length = 0; break; }}function createOption(ddl, text, value) { var opt = document.createElement('option'); opt.value = value; opt.text = text; ddl.options.add(opt);}
<select id="ddl" onchange="configureDropDownLists(this,document.getElementById('ddl2'))"> <option value=""></option> <option value="Colours">Colours</option> <option value="Shapes">Shapes</option> <option value="Names">Names</option></select><select id="ddl2"></select>

蓝山帝景
TA贡献1843条经验 获得超7个赞
(function() { //setup an object fully of arrays //alternativly it could be something like //{"yes":[{value:sweet, text:Sweet}.....]} //so you could set the label of the option tag something different than the name var bOptions = { "yes": ["sweet", "wohoo", "yay"], "no": ["you suck!", "common son"] }; var A = document.getElementById('A'); var B = document.getElementById('B'); //on change is a good event for this because you are guarenteed the value is different A.onchange = function() { //clear out B B.length = 0; //get the selected value from A var _val = this.options[this.selectedIndex].value; //loop through bOption at the selected value for (var i in bOptions[_val]) { //create option tag var op = document.createElement('option'); //set its value op.value = bOptions[_val][i]; //set the display label op.text = bOptions[_val][i]; //append it to B B.appendChild(op); } }; //fire this to update B on load A.onchange();})();
<select id='A' name='A'> <option value='yes' selected='selected'>yes <option value='no'> no</select><select id='B' name='B'></select>
添加回答
举报
0/150
提交
取消