gpt4 book ai didi

javascript - 如何在php中获取下拉值

转载 作者:行者123 更新时间:2023-11-30 12:24:50 25 4
gpt4 key购买 nike

大家好,我正在开发 PHP 应用程序,我使用 javascript 根据另一个下拉框选择填充一个下拉框 - 一切正常,但第二个下拉框值是数字 ,我的问题是如何将第二个保管箱的值设置为文本而不是我得到的数字

下拉框的代码如下:

    <!-- Our food group drop down-->
<select id="foodgroups" onchange="selectFoods(this.options[this.selectedIndex].id)">
<option id="1" value="">Select a Food Group</option>
<option id="2"value="Fruit">Fruit</option>
<option id="3" value="Vegetables">Vegetables</option>
<option id="4" value="Meat">Meat</option>
<option id="5" value="Dairy">Dairy</option>
<option id="6" value="Grains">Grains</option>
</select>

<!-- Our foods for a group selection (empty on default) -->


<select id="foods" name="selectedFoodItem"></select>

这是填充第二个下拉列表的函数

 function selectFoods(foodGroup) {
// Get a reference to the foods select.
var foodsSelect = document.getElementById("foods");

// Create a two dimension array containing foods for each group.
var foods = [["Banana","Grapes","Oranges","Watermelon"],
["Brocolli", "Califlower","Spinach","Tomatoes"],
["Beef", "Chicken", "Turkey", "Tuna"],
["Cheese", "Ice Cream", "Milk", "Yogurt"],
["Bread", "Pasta", "Rice", "Quinoa"]];

if ((foodGroup >= 0) && (foodGroup <= foods.length)) {
foodsSelect.options.length = 0;

// Index was in range, so access our array and create options.
for (var i = 0; i < foods[foodGroup - 1].length; i++) {
foodsSelect.options[foodsSelect.options.length] = new Option(foods[foodGroup - 1][i], i);
}

}
}

我试图访问 php $val = $_POST['selectedFoodItem']; 中的值我得到索引

谢谢!

最佳答案

由于这行代码,您的 PHP 代码获得了索引而不是您期望的字符串值:

new Option(foods[foodGroup - 1][i], i);

第一个参数是您在选择中看到的值,而第二个参数是提交给服务器端的值。在您的示例中,其中一个选项将呈现如下:

<option value="0">Brocolli</option>

如果您希望服务器端接收“Broccoli”,请按如下方式更改选项代码:

new Option(foods[foodGroup - 1][i], foods[foodGroup - 1][i]);

结果是:

<option value="Brocolli">Brocolli</option>

示例 http://jsfiddle.net/4298w4ob/

关于javascript - 如何在php中获取下拉值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29764926/

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