Stefan L
Stefan L

Reputation: 39

Filter <select> options depending on chosen option from another <select>

I need a help with something :

I have two drop down menus (HTML select ) : State and City.

In state select elements, there are choices of different states .

In City there are options which are named in form : State-City (for example Brazil-Sao Paolo). In this second drop down there are all cities with all countries listed.

Now I need to do following :

When I pick up a State from first drop down, I need to make a kind of filter, so when i pick a Brazil from first drop down, second drop-down need to be automatically filtered to only cities which begins with Brazil-...

http://marbestates.com/

The searching form at the top of the page-please look city and location

I suppose that can be done with jQuery , but I need some hints, jsfiddle etc.

Thank you in advance

Upvotes: 1

Views: 7675

Answers (2)

Hadi R.
Hadi R.

Reputation: 413

$("#select1").change(function() {
if ($(this).data('options') === undefined) {
  /*Taking an array of all options-2 and kind of embedding it on the select1*/
 $(this).data('options', $('#select2 option').clone());
 }
 var id = $(this).val();
 var options = $(this).data('options').filter('[value=' + id + ']');
 $('#select2').html(options);
 });

Upvotes: 1

Bhushan Kawadkar
Bhushan Kawadkar

Reputation: 28523

Try this : You can filter option on the basis of state selected and show all of them. You need to set default selected city from visible cities.

Sample HTML:

<select id="state">
    <option>Brazil</option>
    <option>Ghana</option>
</select>

<select id="city">
    <option>Brazil-city1</option>
    <option>Brazil-city2</option>
    <option>Brazil-city3</option>
    <option>Ghana-city1</option>
    <option>Ghana-city2</option>
</select>

jQuery:

$(function(){
    //function to show city
    var showCity = function(selectedState){
     $('#city option').hide();
        $('#city').find('option').filter(function(){
            var city = $(this).text();
            return city.indexOf(selectedState)!=-1;
        }).show();
        //set default value
        var defaultCity = $('#city option:visible:first').text();
        $('#city').val(defaultCity);
    };

    //set default state
    var state = $('#state').val();
    showCity(state);

    //on change event call showCity function 
    $('#state').change(function(){
       showCity($(this).val());
    });
});

JSFiddle Demo

Upvotes: 0

Related Questions