user3632027
user3632027

Reputation: 3

How to filter a dropdown list based from the text on a already pre selected list

I am trying to filter the dropdown list based on the text from 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>

The thing is that the user input is not required,as the list is pre-selected, in this case 'United States'. The output in the dropdown should have only contain 'United States' with the other countries hidden.

I had asked a similar question before which was answered here.

But I am looking for a way to do this by using the text only from the list menu, that is by making no changes to the existing HTML.

Upvotes: 0

Views: 1111

Answers (2)

Hossein Salmanian
Hossein Salmanian

Reputation: 763

i'm not sure why you want a list that has only one item but you can use this code to hide unselected items

$('option:contains("' + $('.selected').text() + '")').siblings().hide();

Upvotes: 1

user2363071
user2363071

Reputation: 249

I would have thought that this would work, but it doesn't for me:

$('select#CountryCode').find('option[text="' + $('ul>li.selected').text() + '"]').prop("selected", true);

Instead, this will do the job:

$('select#CountryCode option').each(function () {
if ($(this).text() == $('ul>li.selected').text())
{
     $(this).prop("selected", true);   
}

});

Have a play with it here:

http://jsfiddle.net/B8tMU/

Upvotes: 0

Related Questions