替换XML驱动的下拉列表中的值

时间:2014-02-21 17:47:07

标签: javascript jquery html

在我的表单中,当用户选择REGION时,会从xml文件中填充下拉菜单。我在REGION中有多个选项。现在,当用户选择不同的选项时,DROPDOWN列表“追加”。我想要它取代。有关如何调整此代码的任何想法吗?

PS ...我知道在JS代码中我有一个“AppendTo”方法。它只是一个功能的占位符。

DROPDOWN HTML:
<select class="t2_drop_field" id="AppType1"></select>

REGION SELECT HTML:
<select name="OBKey__500_1" id="Region" multiple onchange="setAppOptions()">
    <option>Area 1</option>
    <option>Area 1</option>
</select>



var e = document.getElementById("Region");
var eVal=e.options[e.selectedIndex].text;

if (eVal == "J15 KY B" || eVal == "J15 OH B")
    {
            $(document).ready(function() {
            var app_data;      

             // Loading APP
             $.get('pe_form_options.xml', function(data) {
                 app_data = data;
                 var that = $('#AppType1');
                    $('RegionB', app_data).each(function() {
                       $('<option />', { 
                           text: $(this).text(),
                           value: $(this).attr('index')
                       }).appendTo(that);
                    });
             }, 'xml');
         }); 

2 个答案:

答案 0 :(得分:0)

我并非100%确定这是您想要的,但为了替换<select>中的选项,您需要删除旧选项,然后再添加新内容。

最简单的方法是修改你的代码:

...
var that = $('#AppType1');
that.find('option').remove();
$('<option />', { 
    text: $(this).text(),
    value: $(this).attr('index')
}).appendTo(that);
...

我添加的行that.find('option').remove();会在<option>标记下找到所有<select>个标记并将其删除。

答案 1 :(得分:0)

我认为这更直接。谢谢各位的帮助。

     var dv = document.getElementById('AppType1').value;
        if (dv != ""){
            document.getElementById('AppType1').options.length = 0;
        }