0
votes

I have two drop-downs and a text box. First drop down is a list with static values. Second drop down is dynamically filled from a json array. Here is what I would like to achieve. Filter the second drop down based on the value selected from the first drop down. And the text box will output the value based on the selected value from the second drop down. Here is where I am currently: On change I am able to populate the 2nd drop-down and able to output the matched value to the text-box. However my 2nd drop down not being filtered properly. Instead it populates all the available option values. I checked different posts here and tried filtering values before appending but, no avail so far.

HTML:

<select name="make"  id="make">
<option value="0">Select Make:</option>
<option value="1">Acura</option>
<option value="2">BMW</option>
</select>

<select name="model" id="model">
<option value="model">Select Model</option>
</select>

<label for="CarSize"> Your car's size is : </label>
<input type="text" name="carsize" id="size">

Script:
var a = {
Cars:[
  {
    "id":1,
    "make":"Acura",
    "model":"2.2CL/3.0CL",
    "size":"Car"
  },
{
    "id":12,
    "make":"Acura",
    "model":"RDX ",
    "size":"Compact SUV"
 },    
{
    "id":10,
    "make":"Acura",
    "model":"MDX",
    "size":"Large SUV"
  },
 {
    "id":74,
    "make":"BMW",
    "model":"128",
    "size":"Car"
  },
  {
    "id":75,
    "make":"BMW",
    "model":"135",
    "size":"Car"
 },
{
    "id":129,
    "make":"BMW",
    "model":"X3 ",
    "size":"Compact SUV"
  },
  {
    "id":130,
    "make":"BMW",
    "model":"X5",
    "size":"Large SUV"
  }
]
};
   $("#make").change(function(){
if ("#model" !='Select Model')
           $('#model').empty().append($('<option></option>').val('Select Model').html('Select Model'));
else;
            $.each(a.Cars, function (key, value) {
           $("#model").append($('<option></option>').val(value.size).html(value.model

));

});
});

$('#model').change(function () {
    //alert($(this).val());
    //var getModelval = $('#model').val();
    $('#size').val($(this).val());
    //$('#size').val(.val(id));

});

Here is a fiddle link: http://jsfiddle.net/kamuflaj/6vvfr/9/

1
Take a look at this link for some options on how to filter JSON data.Goose

1 Answers

1
votes

There are several options for JSON filtering. Below is one way you can change your onchange event to filter the model dropdown.

$("#make").change(function () {
    $('#model').empty().append($('<option></option>').val('Select Model').html('Select Model'));
    var matchVal = $("#make option:selected").text();
    a.Cars.filter(function (car) {
        if (car.make == matchVal) {
            $("#model").append($('<option></option>').val(car.size).html(car.model));
        }
    });
});

Here is an updated fiddle.