jQuery函数 - 使用其他列表中的下拉列表选择填充的简单下拉列表选项

时间:2016-11-17 21:51:30

标签: jquery mobile selection

您好,乍一看,这似乎与Stack Overflow上的其他帖子重复,但事实并非如此。我已经搜索了我的问题的答案,虽然我找到了一些好的片段并使用了一些信息。我的问题的直接答案不存在。

快速说明:我也在其他论坛上问过这个问题。我觉得这可能最终会帮助很多开发人员,所以即使我在其他地方得到答案(或者在此之前弄清楚),我也会在这里发布。

我想做的事情,简单明了:

  1. 在“第一个下拉列表(水果)”中选择一个选项。
  2. 根据第一个选择,在“第二个下拉列表(Fruit_Types)”上设置默认值。
  3. 最佳地,与第一个选择值相关的所有值(在Fruit_Types下)将填充在第二个选择框中。

    1. 使用一个小的jQuery函数执行此操作,并且在选择列表中没有引用jQuery。换句话说,我应该能够将其放入任何两个相关列表的html页面(参见代码),它应该可以工作。 jquery应该是完全自治的。
    2. 我很感激任何帮助。

      如果有人可以帮助我正常工作,请告诉我。谢谢。

      大部分工作已经完成(参见代码),但我希望每次都能一直工作。到目前为止它只能在这些条件下工作:

      1. 在页面刷新/加载

      2. 页面加载后一次

      3. 然后它停止工作。

        #Start Code

        <!DOCTYPE html>
        <html>
        <head>
        <title>Select one value based on the selection of another</title>
        <meta charset="utf-8">
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
        <script>
        
        jQuery(document).ready(function($) {
        
        jQuery( "#Fruit" )
         .change(function () {
          var str = "";
           jQuery('option:selected', this).each(function() {
            str += jQuery( this ).text() + " ";
            //Added with help from Chainat, Stack Overflow
             jQuery("#Fruit_Types option").removeAttr('selected');
            jQuery("#Fruit_Types option:contains(" + str + ")").first().attr('selected', 'selected');
             });
           })
        .change();
        
        });
        
        </script>
        
        </head>
        <body>
        
        <p>Select the top list and the second list should populate with the corresponding related values.</p>
        
        <select id="Fruit">
        <option id="1">Apples</option>
        <option id="2">Oranges</option>
        </select>
        
        &nbsp;
        
        <select id="Fruit_Types">
        <option id="3">Apples Green</option>
        <option id="4">Apples Red</option>
        <option id="5">Apples Granny Smith</option>
        <option id="6">Apples Fuji</option>
        <option id="7">Oranges California</option>
        <option id="8">Oranges Florida</option>
        <option id="9">Oranges Blood</option>
        <option id="10">Oranges Seedless</option>
        </select>
        
        </body>
        </html>

        #结束代码

1 个答案:

答案 0 :(得分:0)

首先,代码不断向第二个列表中的所有项添加selected属性。您需要先删除它们,也可能只想在第二个列表中选择一个项目。此代码将解决该问题

 jQuery("#Fruit_Types option").removeAttr('selected');
 jQuery("#Fruit_Types option:contains(" + str + ")").first().attr('selected', 'selected');

如果您只想在第二个列表中显示相关项目,您可以考虑将水果类型保存在变量或其他内容上,并根据所选水果项目动态填充它们。

相关问题