【问题标题】:html dynamically filter a select options according to values in another select tag in javascripthtml根据javascript中另一个选择标签中的值动态过滤选择选项
【发布时间】:2017-01-18 01:24:18
【问题描述】:

我有两个 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 是一个完整的国家/地区列表,其代码已经填充:

    <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 标记,根据第一个从完整下拉列表中添加选项? ..是否有解决方案只过滤第二个 SELECT tAG 中的全名列表以仅保留第一个中加载的选项? ...我知道这是 sql 或 ms-access 的纳秒工作!.. 但是可以使用 html 和 javascript 来完成吗? 我很感激所有的答案。

【问题讨论】:

    标签: javascript html html-select


    【解决方案1】:

    你最好在 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');
    

    【讨论】:

    • 请问如何使用此代码? ..在我的 html 页面中?
    • 非常感谢您的回答,我刚刚对其进行了测试并且工作正常!但请完成此操作,如何从新创建的 Select 标记中获取选项值:我的意思是(参考您的 html 代码)当我从创建的 Select 中选择 A 或 C 时,我需要获取 a 或 c 。这个值我必须使用它将访问者重定向到页面( location.href = "xxx.php#" + value;))
    • $filtered.on('change', function() { location.href = '#' + $(this).val(); });
    • 你救了我!太感谢了 !我很欣赏阿格丹。
    • 您好,我真的不想打扰您,但是有没有办法在 javascript(不是 Jquery)中执行相同的例程?
    猜你喜欢
    • 2017-02-21
    • 1970-01-01
    • 2017-12-26
    • 1970-01-01
    • 2013-05-03
    • 2020-11-22
    • 2015-09-20
    • 2017-05-04
    • 1970-01-01
    相关资源
    最近更新 更多