How to filter a dropdown list based on a already p

2019-09-22 06:02发布

问题:

I am trying to filter the dropdown list based on the first pre-selected list. The first list is contains 'United States' as pre selection and the list to be filtered is the second drop down menu. I would appreciate inputs on how to solve this.

<ul>
    <li class="">Argentina</li>
    <li class="selected">United States</li>
    <li class="">Australia</li>
</ul>
<select data-val="false" data-val-length="Only 64 characters allowed." data-val-length-max="64" data-val-required="Country code can't be empty" id="CountryCode" name="CountryCode" class="valid">
    <option value="ARG">Argentina</option>
    <option value="USA">United States</option>
    <option value="AUS">Australia</option>
</select>

Regards,

Adit

回答1:

jQuery

Get the selected country and then find the <option> using attribute-equals-selector and hide the siblings

$(function () {
    var country = $('.selected').data('country');
    $('#CountryCode').find('[value="' + country + '"]').siblings().hide();
    $('#CountryCode').val(country);
});

HTML

Add data-* attribute to the html elements

<ul>
    <li data-country="ARG">Argentina</li>
    <li data-country="USA" class="selected">United States</li>
    <li data-country="AUS">Australia</li>
</ul>

DEMO