gpt4 book ai didi

javascript - 从下拉框中添加和选择选项值

转载 作者:行者123 更新时间:2023-11-30 18:13:46 27 4
gpt4 key购买 nike

我需要你的帮助来创建一个函数,该函数允许我根据给定的 var 从下拉框中选择给定的选项名称(使用 javascript)如果该值不存在,则将其添加到下拉列表中,然后选择它。

例子:

<html>

<head>

<script type="text/javascript">

function test() {

var option_name_to_look_for = "mangos"

if option_name_to_look_for is listed in the drop down box (drop) then select it

if the option_name_to_look_for is not listed in the drop down box (drop), automatically add it to the drop down list (drop) and select it.

}

</script>

</head>

<body>

<select id="drop" style="width: 200px;">
<option value="0"></option>
<option value="1">apples</option>
<option value="2">oranges</option>
<option value="3">pears</option>
<option value="4">mangos</option>
<option value="5">bananas</option>
<option value="6">kiwis</option>

</select>

</body>

</html>

最佳答案

非 jQuerified 版本!

function selectMe(name){
var select = document.getElementById("drop"),
options = select.options,
found = false;

//Search for it!
for (var x=0; x<options.length; x++){
if(options[x].text==name){
options[x].selected=true;
found = true;
break;
}
}

//if it isn't found, add it!
if(!found){
var option = document.createElement("option");
option.text = name;
option.value = options.length;
select.appendChild(option);
option.selected=true;
}
}

selectMe("mangos");

关于javascript - 从下拉框中添加和选择选项值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13882100/

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