Conditional dropdownlist using jquery or javascrip

2019-08-27 10:15发布

问题:

Conditional dropdownlist using jquery or javascript only

Scenario: I have a main dropdownlist list and if i select 'dropdownmain1' on my dropdownlist it will show dropdownlist corresponding valuues for 'dropdownmain1'

<select name="dropdownmain" id="" title="">
    <option value="dropdownmain1">dropdownmain1</option>
    <option value="dropdownmain2">dropdownmain2</option>
    <option value="dropdownmain3">dropdownmain3</option>
    <option value="dropdownmain4">dropdownmain4</option>
</select>



//if selected dropdownmain1 this dropdown will display
<select name="dropdownmain1" id="" title="">
    <option value="dropdownmain1-submenu1">dropdownmain1-submenu1</option>
    <option value="dropdownmain1-submenu2">dropdownmain1-submenu2</option>
    <option value="dropdownmain1-submenu3">dropdownmain1-submenu3</option>
    <option value="dropdownmain1-submenu4">dropdownmain1-submenu4</option>
</select>

//if selected dropdownmain2 this dropdown will display
<select name="dropdownmain2" id="" title="">
    <option value="dropdownmain2-submenu1">dropdownmain2-submenu1</option>
    <option value="dropdownmain2-submenu2">dropdownmain2-submenu2</option>
    <option value="dropdownmain2-submenu3">dropdownmain2-submenu3</option>
    <option value="dropdownmain2-submenu4">dropdownmain2-submenu4</option>
</select>

//if selected dropdownmain3 this dropdown will display
<select name="dropdownmain3" id="" title="">
    <option value="dropdownmain3-submenu1">dropdownmain3-submenu1</option>
    <option value="dropdownmain3-submenu2">dropdownmain3-submenu2</option>
    <option value="dropdownmain3-submenu3">dropdownmain3-submenu3</option>
    <option value="dropdownmain3-submenu4">dropdownmain3-submenu4</option>
</select>

//if selected dropdownmain4 this dropdown will display
<select name="dropdownmain4" id="" title="">
    <option value="dropdownmain4-submenu1">dropdownmain4-submenu1</option>
    <option value="dropdownmain4-submenu2">dropdownmain4-submenu2</option>
    <option value="dropdownmain4-submenu3">dropdownmain4-submenu3</option>
    <option value="dropdownmain4-submenu4">dropdownmain4-submenu4</option>
</select>

is this possible using jquery or javascript only?

回答1:

Yes you can do it easily with jquery.

$('select[name!="dropdownmain"]').hide();
$('select[name="' + $('select[name="dropdownmain"]').val() + '"]').show();
$('select[name="dropdownmain"]').change(function(){
    $('select[name!="dropdownmain"]').hide();
    $('select[name="' + $(this).val() + '"]').show();
});

http://jsfiddle.net/p7jyv/2/

And a more readable approach:

var $topSelect = $('select[name="dropdownmain"]');
var $nestedSelects = $('select[name!="dropdownmain"]');
showApplicableSelect();
$topSelect.change(showApplicableSelect);
function showApplicableSelect() {
    $nestedSelects.hide();
    $('select[name="' + $topSelect.val() + '"]').show();
}

http://jsfiddle.net/p7jyv/5/