javascript,用一个数组动态填充下拉列表,该数组来自文本字段中键入的值

javascript to dynamically populate dropdown with an array from value typed into text field

本文关键字:数组 文本 字段 填充 javascript 动态 一个 下拉列表      更新时间:2023-09-26

嗨,这里有一个代码示例:http://jsbin.com/oxoweh

我的问题是,我无法获得输入到文本框中的值,因此当单击选择按钮时,第二个下拉列表将仅显示与输入到文本盒中的内容相关的数据。例如,如果在文本框中输入了水果,我希望子类别下拉菜单中包含所有水果,而不是使用现有的类别下拉菜单

http://jsfiddle.net/goldentoa11/P3hs8/1/

我在"SelectSubCat()"中添加了一个名为txtValue的参数。这样您就可以传递要进行比较的值。

当你调用"SelectSubCat()"函数时,你需要用文本字段的值来调用它。我在文本字段中添加了一个名为"selectText"的id,当我点击按钮时,我添加了

onclick="SelectSubCat(document.getElementById('selectText').value)"

这将使用输入的文本调用函数。然后,它不使用表单中的值,而是使用传递给它的值,并创建相应的子类别。最后,您需要更改Category的"onchange"函数,以便只传递一个空字符串。

function SelectSubCat(txtValue) {
if(txtValue == "") txtValue = document.drop_list.Category.value;
// This line is to set txtValue to Category's value if the current value is blank. 
// In other words, if it was called by changing the dropdown, 
// give it the drop down's value.
// ON selection of category this function will work
removeAllOptions(document.drop_list.SubCat);
addOption(document.drop_list.SubCat, "", "SubCat", "");
if (txtValue == 'Fruits') {
    addOption(document.drop_list.SubCat, "Mango", "Mango");
    addOption(document.drop_list.SubCat, "Banana", "Banana");
    addOption(document.drop_list.SubCat, "Orange", "Orange");
}
if (txtValue == 'Games') {
    addOption(document.drop_list.SubCat, "Cricket", "Cricket");
    addOption(document.drop_list.SubCat, "Football", "Football");
    addOption(document.drop_list.SubCat, "Polo", "Polo", "");
}
if (txtValue == 'Scripts') {
    addOption(document.drop_list.SubCat, "PHP", "PHP");
    addOption(document.drop_list.SubCat, "ASP", "ASP");
    addOption(document.drop_list.SubCat, "Perl", "Perl");
}
}