gpt4 book ai didi

javascript - 根据另一个下拉列表填充一个下拉列表并获取 "value"而不是下拉列表显示值

转载 作者:行者123 更新时间:2023-12-02 23:59:24 26 4
gpt4 key购买 nike

我正在尝试创建两个下拉菜单,并由另一个下拉菜单填充

这是代码

html

<form type=get action="action.php">
<select name="meal" id="meal" onChange="changecat(this.value);">
<option value="" disabled selected>Select</option>
<option value="A">A</option>
<option value="B">B</option>
<option value="C">C</option>
</select>
<select name="category" id="category">
<option value="" disabled selected>Select</option>
</select>
<input type="submit">
</form>

JavaScript

<script>

var mealsByCategory = {
A : {one:"Soup", two:"Juice"},
B : {three:"Water", four:"Others"},
C : {five:"Coffee", six:"Tea"}
};

function changecat(value) {
if (value.length == 0) document.getElementById("category").innerHTML = "<option></option>";
else {
var catOptions = "";
for (categoryId in mealsByCategory[value]) {
catOptions += "<option value='" + mealsByCategory[value][categoryId] +"'>" + mealsByCategory[value][categoryId] + "</option>";
}
document.getElementById("category").innerHTML = catOptions;
}
}

</script>

我知道我的java脚本没有错误。

我正在寻找类似下拉值中的输出,其中值必须是对象名称,而在 dropdrown 中则为对象值。

即当我点击提交时网站去action.php?meal=B&category=Juice

在这里您可以看到果汁被传递(在下拉菜单中出现),而不是我需要传递“two”,这是果汁的对象名称

action.php?meal=B&category=two

最佳答案

分配categoryId作为选项的值

var mealsByCategory = {
A: {
one: "Soup",
two: "Juice"
},
B: {
three: "Water",
four: "Others"
},
C: {
five: "Coffee",
six: "Tea"
}
};

function changecat(value) {
if (value.length == 0) document.getElementById("category").innerHTML = "<option></option>";
else {
var catOptions = "";
for (categoryId in mealsByCategory[value]) {
catOptions += "<option value='" + categoryId + "'>" + mealsByCategory[value][categoryId] + "</option>";
}
document.getElementById("category").innerHTML = catOptions;
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<form type=get action="action.php">
<select name="meal" id="meal" onChange="changecat(this.value);">
<option value="" disabled selected>Select</option>
<option value="A">A</option>
<option value="B">B</option>
<option value="C">C</option>
</select>
<select name="category" id="category">
<option value="" disabled selected>Select</option>
</select>
<input type="submit">
</form>

关于javascript - 根据另一个下拉列表填充一个下拉列表并获取 "value"而不是下拉列表显示值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55242382/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com