html根据javascript中另一个select标记中的值动态过滤选择选项

时间:2016-12-20 08:02:00

标签: javascript html html-select

我有两个Select标签:第一个是动态填充php脚本(扫描我的非空文件夹)并给我国家代码如下:

         <select name="countries" id="countries"> 
         <option>fr</option>
         <option>gr</option>
         <option>it</option>
         <option>gr</option>
         <option>pl</option>
         <option>gb</option>
         <option>es</option>
         <option>pt</option>
                  ... 
         (dynamically populated from a php script)
    </select>

并且第二个SELECT是已填充其代码的countrie的完整列表:

    <select name="ctCodes" id="ctCodes">
    <option>--select--</option>
    <option value="fr">France</option>
    <option value="nl">Netherlands</option>
    <option value="bl">Belgium</option>
    <option value="rs">Russia</option>
                   ... 
      (full ready list with all countries and code as value)
    </select>

我不希望我的访客从第一个SELECT中选择,因为它只是代码(fr,de,..)但我希望他从全名列表中选择全名国家(法国,德国...... )其中选项值将他重定向到所选国家:例如,他选择德国,我的函数将采用他:location.href =“xxx.php#”+ element.value;)在这种情况下'de'。

我如何实现这一点:创建第三个SELECT标签,根据第一个标签从完整下拉列表中添加OPTIONS? ..有一个解决方案只是过滤第二个SELECT标签中的全名列表,只保留第一个加载的选项吗? ...我知道这是sql或ms-access的纳秒级工作!..但是有可能用html和javascript做到这一点吗? 我很感激所有答案。

1 个答案:

答案 0 :(得分:0)

您最好在php中生成此过滤后的选择,因为您已经拥有了所需的国家/地区代码和全名。但是,由于您可能无法使用jQuery更改这些javascript解决方案:

var countryCodes = [],
    $filtered;

$('#countries option').each(function() {
    countryCodes.push($(this).text());
});

$filtered = $('#ctCodes').clone();
$filtered.attr('id', 'filtered');

$filtered.find('option').each(function() {
    var $this = $(this);
    if (countryCodes.indexOf($this.val()) === -1) {
        $this.remove();
    }
});

$filtered.insertAfter('#ctCodes');