gpt4 book ai didi

javascript - 如何检索下拉列表中的数组值列表

转载 作者:行者123 更新时间:2023-11-28 07:10:51 25 4
gpt4 key购买 nike

我想填充下拉列表中的值列表。

这是我尝试过的代码,但我不知道如何继续处理数组值列表。请提出建议,以便我能够完成我的任务。

<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function populate_dropdown(country)
{
switch(country)
{
case "america":
document.forms[0].states.length = 2;
document.forms[0].states.disabled = false;
document.forms[0].states.options[0].text = 'Washington';
document.forms[0].states.options[0].value = 'Washington';
document.forms[0].states.options[1].text = 'Florida';
document.forms[0].states.options[1].value = 'Florida';

break;
case "india":
document.forms[0].states.length = 2;
document.forms[0].states.disabled = false;
document.forms[0].states.options[0].text = 'Orissa';
document.forms[0].states.options[0].value = 'Orissa';
document.forms[0].states.options[1].text = 'Punjab';
document.forms[0].states.options[1].value = 'Punjab';
break;
default:
document.forms[0].states.length = 1;
document.forms[0].states.options[0].text = 'Select a country first';
document.forms[0].states.disabled = true;
}
}
</script>

</head>
<body>
<form action="this.html" method="post">
<p>
<input id="America" type="radio" name="country" value="America" onclick="populate_dropdown('america')" /><label for="America">America</label><br />
<input id="India" type="radio" name="country" value="India" onclick="populate_dropdown('india')" /><label for="India">India</label><br />

<select disabled="disabled" name="states">
<option>Select a country first</option>
</select>
</p>
</form>
</body>
</html>

最佳答案

你想要这样的东西吗?

states = {
"america": [
{ "text": "Washington", "value": "Washington" },
{ "text": "Florida", "value": "Florida" },
],
"india": [
{ "text": "Orissa", "value": "Orissa" },
{ "text": "Punjab", "value": "Punjab" },
],
};

function populate_dropdown(country) {
if(!states[country]) {
document.forms[0].states.options = [];
document.forms[0].states.disabled = true;
return;
}

document.forms[0].states.options.length = 0;
for(var i = 0; i < states[country].length; i++) {
var state = states[country][i];
document.forms[0].states.options[i] = new Option(state.text, state.value, false, false);
}
document.forms[0].states.disabled = false;
}
<form action="this.html" method="post">
<p>
<input id="America" type="radio" name="country" value="America" onclick="populate_dropdown('america')" />
<label for="America">America</label>
<br />
<input id="India" type="radio" name="country" value="India" onclick="populate_dropdown('india')" />
<label for="India">India</label>
<br />
<select disabled="disabled" name="states">
<option>Select a country first</option>
</select>
</p>
</form>

关于javascript - 如何检索下拉列表中的数组值列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31316002/

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