karthi
karthi

Reputation: 27

filter select box options using jquery

I have two selection boxes,one contains different country names and another contains all state names of all countries.

Then if i select India from country selection box, the state selection box has need to show all states of India alone and remove all other states from it.

I need to do this in JQuery, any one is there to guide me!!!!!

Upvotes: 0

Views: 1012

Answers (2)

S L
S L

Reputation: 14318

Create an array of states under array of countries, and onchange event append it to the states.

<script>


var states = [];

states['India'] = ["state 1", "state 1", "state 1"];



states['China'] = ["state 2", "state 2", "state 3"];


$(document).ready(function (){


    $('#country').change(
        function(){

            var temp = states[$(this).val()];

            $('#states').children().remove();

            for(var j=0; j<temp.length; j++){

                $('<option></option>').html(temp[j]).appendTo($('#states'));

            }

        }       
    )


})


</script>

<select id="country">
    <option id="India">India</option>
    <option id="Nepal">Nepal</option>       
    <option id="China">China</option>       
    <option id="Mongolia">Mongolia</option>             
    <option id="Russia">Russia</option>                     
</select>   

<select id="states">
    <option>null</option>
</select>

Upvotes: 2

xkeshav
xkeshav

Reputation: 54022

U better use different way

make two select box one is for country and another for state ( default disable) when usee select country from first select box then get all state of that country via ajax in second select box..

that will be better way instead of upload all state together and then filter

Upvotes: 1

Related Questions