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

后端 未结 2 1644
孤城傲影
孤城傲影 2020-12-10 09:35

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 cod

2条回答
  •  不思量自难忘°
    2020-12-10 10:13

    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.

    $(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/

    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.

    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.

    $(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/

提交回复
热议问题