开发者

Updating Selectbox options

开发者 https://www.devze.com 2023-03-22 09:08 出处:网络
I have 2 Selectbox Countrynames 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

I have 2 Selectbox

  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

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

now i have to replace 开发者_开发百科only the options of select tag. 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. You will have to change the way your ajax is returning airport names. Instead of <option>abc</option><option>xyz</option> return a string of names seperated by for example || : 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. 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>
0

精彩评论

暂无评论...
验证码 换一张
取 消