根据另一个下拉列表填充一个下拉列表,并获取“值”,而不是显示值的下拉列表

时间:2019-03-19 13:38:09

标签: javascript arrays json html5

我正在尝试创建两个下拉列表,并在另一个下拉列表中填充

这是代码

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脚本没有错。

我正在寻找输出,例如下拉列表中的值必须是对象名称,而下拉列表中的则必须是对象值。

ie 当我点击提交 去现场 action.php?meal=B&category=Juice

在这里您可以看到果汁通过了(下拉时会消失),而不是果汁,我需要传递“两个”作为果汁的对象名称

action.php?meal=B&category=two

1 个答案:

答案 0 :(得分:1)

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>