简体   繁体   English

更新选择框选项

[英]Updating Selectbox options

I have 2 Selectbox我有 2 个选择框

  1. Countrynames国名
  2. Airports机场

And as I select a countryname in first selectbox an Ajax request will be sent and it returns a list of Airposts as options like当我 select 在第一个选择框中的国家/地区名称时,将发送 Ajax 请求,并返回 Airposts 列表作为选项,例如

"
<option value='1'>abc
<option value='3'>lmn
<option value='2'>xyz
"

now i have to replace only the options of select tag.现在我只需要替换 select 标签的选项。 i am trying to do something like我正在尝试做类似的事情

var country_select = document.getElementById("country_select");
country_select.options.length = 0;
country_select.options = response.responseText

but this assignment is not working how may i get it done!但是这个任务不起作用我怎么能完成它!

Try尝试

var country_select = document.getElementById("country_select");
country_select.innerHTML = response.responseText;

This is a little bit more tricky, you won't be able to do it using innerHTML or anything like that.这有点棘手,您将无法使用 innerHTML 或类似的东西来做到这一点。 You will have to change the way your ajax is returning airport names.您将不得不更改 ajax 返回机场名称的方式。 Instead of <option>abc</option><option>xyz</option> return a string of names seperated by for example ||: abc||def||xyz .而不是<option>abc</option><option>xyz</option>返回由例如 ||: abc||def||xyz分隔的名称字符串。 then explode the string into an array in JS, create an option elements from every element in array, and add it to dropdown.然后将字符串分解为 JS 中的数组,从数组中的每个元素创建一个选项元素,并将其添加到下拉列表中。 check that:检查:

<html>
<head>
    <script>
        var ajaxResponse = "abs||def||xyz||test||blah";

        function updateOptions( optionsString )
        {
            var options = optionsString.split("||");

            for( var i=0; i< options.length; i++ )
            {
                AddItem( options[i], options[i] );
            }
        }

        function AddItem(Text,Value)
        {
            var opt = document.createElement("option");
            opt.text = Text;
            opt.value = Value;

            document.getElementById("mydropdown").options.add(opt);
        }

        function removeOptions()
        {
            document.getElementById('mydropdown').length = 0;
        }
    </script>
</head>
<body>
    <input type="button" onclick="updateOptions(ajaxResponse)" value="update"></input>
    <input type="button" onclick="removeOptions()" value="remove"></input>
    <select id="mydropdown">
    </select>
</body>
</html>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM