Javascript jQuery:有条件地显示基于下拉框选择的元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10200498/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 00:17:14  来源:igfitidea点击:

jQuery: Conditional show an element based on drop down box selection

javascriptjquery

提问by TTT

I have two related drop-down lists, in which the contents in the second drop-down list depends on the selection made in the first one. For example, in the following HTML code, you will choose application method first. If you choose Aerial as the application method, then you will answer further question such as aerial size dist. Otherwise, you need to answer ground spray type.

我有两个相关的下拉列表,其中第二个下拉列表中的内容取决于第一个下拉列表中的选择。例如,在下面的 HTML 代码中,您将首先选择应用程序方法。如果您选择Aerial 作为应用方法,那么您将回答更多问题,例如Aerial size dist。否则,您需要回答地面喷雾类型。

So once the webpage is loaded, the two second level drop-down lists (aerial size dist., and ground spray type.) are hidden. They will appear only when related choice is made in the first one (application method).

所以一旦网页加载完毕,两个二级下拉列表(空中尺寸分布和地面喷雾类型)就隐藏了。只有在第一个(申请方法)中做出相关选择时才会出现。

I am able to achieve this feature in jQuery (below jQuery code). But my approach is pretty stupid. My question is:

我能够在 jQuery 中实现此功能(在 jQuery 代码下方)。但我的方法很愚蠢。我的问题是:

  1. Is there a way to select the whole row, without using counting its sequence (nth-child())? Can I choose the whole row, based on selecting an element ID ? For example, can I first select $('#id_A') and then expand my selection to the whole row?

  2. Is there a better way (a loop?) to achieve this hide or show feature rather than comparing all the possible choices (($(this).val() == "X") )?

  1. 有没有办法选择整行,而不使用计算其序列(nth-child())?我可以根据选择元素 ID 选择整行吗?例如,我可以先选择 $('#id_A') 然后将我的选择扩展到整行吗?

  2. 有没有更好的方法(循环?)来实现此隐藏或显示功能,而不是比较所有可能的选择(($(this).val() == "X") )?

Thanks!

谢谢!

Here is the HTML code, and the form is generated by Django:

下面是 HTML 代码,表单由 Django 生成:

<div class="articles">
    <form method="GET" action=_output.html>
        <table align="center">
<tr><th><label for="id_application_method">Application method:</label></th><td><select  name="application_method" id="id_application_method">
<option value="">Pick first</option>
<option value="A">Aerial</option>
<option value="B">Ground</option>
</select></td></tr>

<tr><th><label for="id_A">Aerial Size Dist:</label></th><td><select name="aerial_size_dist" id="id_A">
<option value="A1" selected="selected">A1</option>
<option value="A2">A2</option>
</select></td></tr>

<tr><th><label for="id_B">Ground spray type:</label></th><td><select name="ground_spray_type" id="id_B">
<option value="B1" selected="selected">B1</option>
<option value="B2">B2</option>
</select></td></tr>
</table>                  
</form>
</div>

Here is the jQuery code:

这是jQuery代码:

<script type="text/javascript" src=" https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.js"></script> 

<script>$(function() {
    $("tr:nth-child(2)").hide();
    $("tr:nth-child(3)").hide();

    $('#id_application_method').change(function() {
    ($(this).val() == "A") ? 
    $("tr:nth-child(2)").show() : $("tr:nth-child(2)").hide();

    ($(this).val() == "B") ? 
    $("tr:nth-child(3)").show() : $("tr:nth-child(3)").hide();
    });});</script>

回答by Adrian J. Moreno

Your questions describe the right ideas. You just have to structure your HTML to take advantage of them.

你的问题描述了正确的想法。您只需要构建您的 HTML 以利用它们。

JSFiddle posted here: http://jsfiddle.net/iknowkungfoo/TKamw/

JSFiddle张贴在这里:http: //jsfiddle.net/iknowkungfoo/TKamw/

HTML - I added an ID and CLASS to each TR that match the values in your primary SELECT:

HTML - 我为每个与您的主要 SELECT 中的值匹配的 TR 添加了一个 ID 和 CLASS:

<div class="articles">
    <form method="get" action="_output.html">
        <table align="center">
            <tr>
              <th><label for="id_application_method">Application method:</label></th>
              <td><select name="application_method" id="id_application_method">
                <option value="">Pick first</option>
                <option value="A">Aerial</option>
                <option value="B">Ground</option>
              </select></td>
            </tr>
            <tr id="tr_A" class="method_options">
              <th><label for="id_A">Aerial Size Dist:</label></th>
              <td><select name="aerial_size_dist" id="id_A">
                <option value="A1" selected="selected">A1</option>
                <option value="A2">A2</option>
              </select></td>
            </tr>
            <tr id="tr_B" class="method_options">
              <th><label for="id_B">Ground spray type:</label></th>
              <td><select name="ground_spray_type" id="id_B">
                <option value="B1" selected="selected">B1</option>
                <option value="B2">B2</option>
              </select></td>
            </tr>
        </table>
    </form>
</div>

CSS - hide those TRs by default:
tr.method_options { display: none; }?

CSS - 默认隐藏那些 TR:
tr.method_options { display: none; }?

JavaScript/jQuery - When the primary SELECT changes, hide all TRs with a CLASS of "method_options". Then, Find the TR whose ID matches the value of the selected option in the primary SELECT and show it. If there is no match, then nothing is shown.

JavaScript/jQuery - 当主要 SELECT 更改时,隐藏所有具有“method_options”类的 TR。然后,在主 SELECT 中找到其 ID 与所选选项的值匹配的 TR 并显示它。如果没有匹配项,则不显示任何内容。

$(document).ready(function(){

    $('#id_application_method').on('change', function() {         

        $('tr.method_options').hide();
        $('#tr_' + $(this).val() ).show();

    });

});

回答by Will Klein

I think iKnowKungFoo's answer is very straightforward (it's got my vote). I noticed you said your form is generated by Django though. In case it's not straightforward for you to modify your generated HTML markup, here is another solution to your problem.

我认为 iKnowKungFoo 的回答非常简单(我投票)。我注意到你说你的表单是由 Django 生成的。如果您修改生成的 HTML 标记并不简单,这里是您问题的另一种解决方案。

$(document).ready(function() {
    var $aerialTr = $('#id_A').closest('tr').hide();
    var $groundSprayTr = $('#id_B').closest('tr').hide();

    $('#id_application_method').change(function() {
        var selectedValue = $(this).val();

        if(selectedValue  === 'A') {
            $aerialTr.show();
            $groundSprayTr.hide();
        } else if (selectedValue === 'B') {
            $aerialTr.hide();
            $groundSprayTr.show();
        } else {
            $aerialTr.hide();
            $groundSprayTr.hide();
        }
    });
});

Here is a jsFiddle to test: http://jsfiddle.net/willslab/n54cE/2/

这是一个要测试的 jsFiddle:http: //jsfiddle.net/willslab/n54cE/2/

It should work with your existing markup. It selects the tr's based on the current IDs for the select boxes. If you change those IDs, you will need to modify the selectors accordingly.

它应该适用于您现有的标记。它根据选择框的当前 ID 选择 tr。如果更改这些 ID,则需要相应地修改选择器。

I hope that helps!

我希望这有帮助!

Edit: Here is another alternative, "hybrid" approach inspired by iKnowKungFoo. His solution is very elegant, so I combined it with my own. This works without changes to HTML or CSS.

编辑:这是另一种替代方法,受 iKnowKungFoo 启发的“混合”方法。他的解决方案非常优雅,所以我将其与我自己的结合起来。这无需更改 HTML 或 CSS。

$(document).ready(function() {
    $('#id_A').closest('tr').addClass('method_options').hide();
    $('#id_B').closest('tr').addClass('method_options').hide();

    $('#id_application_method').change(function() {
        $('tr.method_options').hide();
        $('#id_' + $(this).val()).closest('tr').show();
    });
});

jsFiddle link: http://jsfiddle.net/willslab/6ASJu/3/

jsFiddle 链接:http: //jsfiddle.net/willslab/6ASJu/3/