1
state.on('change', function(){
    city.empty();
    $.getJSON("pincodes.JSON", function(pincodes){
        var key = state.val(); 
        for (var j= 0; j < pincodes['address'].length; j++) {
            if (pincodes['address'][j]['circlename'] == key) {
                temp.push(pincodes['address'][j]['regionname']);
            }
        } 
        cities = $.unique(temp);
        for (var k = 0; k < cities.length; k++) {   
            city.append('<option>' + cities[k] + '</option>');
        }  
    });
});

In the above state = $('#state') , the above works fine fills the cities on select "state" . But the issue is when a new state is selected the previously filled cities are also there . Even though I tried .empty on every change() .

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
Neha
  • 11
  • 8

1 Answers1

0

You don't empty your temp array. So, every time this function is called, you keep appending items to your temp array.

You simply need to add the following line in your code:

state.on('change', function() {
    city.empty();
    temp = []; // <---
    $.getJSON("pincodes.JSON", function(pincodes) {

What about cities = $.unique(temp);, it won't work.
According to jQuery.unique() documentation, this function

Sorts an array of DOM elements, in place, with the duplicates removed. Note that this only works on arrays of DOM elements, not strings or numbers.

So, it is not a correct usage. If you get non-unique values from your JSON, you will need to use another way to get distinct values. There is a good SO article on this topic.

Community
  • 1
  • 1
Yeldar Kurmangaliyev
  • 33,467
  • 12
  • 59
  • 101
  • Thanks , cities = $.unique(temp); works for uniques values in my case . I fetch from json in temp which is not unique . the values I get in cities are unique . The only issue was it was not working when change fired more than once . and thanks for the help , it really worked . – Neha Nov 03 '15 at 12:48