Andrei RRR
Andrei RRR

Reputation: 3162

Replace <select> values

I have a jquery script that reads an xml file to replace the <select> values. The script works but my problem is that when I click on different values on #carMake <select> the script adds the options to #carModel <select> instead of replacing them.

Javascript:

    function carMake(){

  $.get('category1.xml', function(d){
      $(d).find('category').each(function(){  
        var $category = $(this);  
        var categoryTitle = $category.attr("name");
        var categoryID = $category.attr("id");    
        var html = '<option value="' + categoryID + '">' + categoryTitle + '</option>';    
        $('#carMake').append($(html));

        $('#loading').fadeOut('slow', function() {
            $('#loading').hide();
        });


    });
  }); 
}

function carModel(){

        $('#loading').fadeIn('fast', function() {
            $('#loading').show();
        });  

  $.get('category2.xml', function(d){
      $(d).find('category').each(function(){  
        var $category = $(this);  
        var categoryTitle = $category.attr("name");
        var categoryID = $category.attr("id");    
        var html = '<option value="' + categoryID + '">' + categoryTitle + '</option>';    
        $('#carModel').append($(html));

        $('#loading').fadeOut('slow', function() {
            $('#loading').hide();
        });  

    });
  }); 
}

carMake();

$('#carMake').change(function() {
    carModel();
});

HTML

            <div class="field"><div class="label">Car Make:</div>
            <select name="carMake" id="carMake" class="value">

            </select>
            </div>
            <div class="field"><div class="label">Car Model:</div>
            <select name="carModel" id="carModel" class="value">

            </select>
            </div>

Upvotes: 0

Views: 91

Answers (2)

K D
K D

Reputation: 5989

It should work correctly.

$.get('category1.xml', function(d){
      $('#carMake').empty();
      $(d).find('category').each(function(){  

        var $category = $(this);  
        var categoryTitle = $category.attr("name");
        var categoryID = $category.attr("id");    
        var html = '<option value="' + categoryID + '">' + categoryTitle + '</option>';    
        $('#carMake').append($(html));

        $('#loading').fadeOut('slow', function() {
            $('#loading').hide();
        });


    });

Upvotes: 1

Ruben Infante
Ruben Infante

Reputation: 3135

Empty the contents of the select at the beginning of your callbacks.

$.get('category1.xml', function(d){
    // Empty the current contents
    $('#carMake').empty();
    $(d).find('category').each(function(){  
        ...
    });
}); 

$.get('category2.xml', function(d){
    // Empty the current contents
    $('#carModel').empty();
    $(d).find('category').each(function(){  
        ...
    });
}); 

Upvotes: 1

Related Questions