jQuery Filter JSON Data

by Suryar Praveen

HTML

<div id="DrpDwn">
        Data:<select id="DropDown_Year"><option>Data</option></select>
        </div>
<br />
Filtered product information
    <table id="details"  border="1" cellpadding="2" cellspacing="2">
    <thead>
        <tr>
            <th>Data</th>
            <th>Country</th>
            <th>Price</th>
        </tr>
    </thead> 
    <tbody></tbody>   
</table>

CSS

th,td
{
   width: 100px;
}

JavaScript

var ProductInfo = [{
    Year: "2011",
    Make: "Product 1",
    Model: "101"
},
{
    Year: "2011",
    Make: "Product 2",
    Model: "x101"
},
{
    Year: "2010",
    Make: "Product 3",
    Model: "234"
},
{
    Year: "2011",
    Make: "Product 4",
    Model: "100"
},
{
    Year: "2012",
    Make: "Product 5",
    Model: "500"
},
{
    Year: "2011",
    Make: "Product 6",
    Model: "100"
},
{
    Year: "2013",
    Make: "Product 7",
    Model: "100"
},
{
    Year: "2013",
    Make: "Product 8",
    Model: "455"
}];
var yearsArray = [];
// adding unique years to yearsArray
$.each(ProductInfo, function (index) {
    var year = ProductInfo[index].Year;
    if ($.inArray(year, yearsArray) == -1) {
        yearsArray.push(year);
    }
});
//sorting the year 
yearsArray.sort();
var $yearDropDown = $("#DropDown_Year");
var $container = $("#details").find("tbody");
// append the years to select
$.each(yearsArray, function (i) {
    $yearDropDown.append('<option value="' + yearsArray[i] + '">' + yearsArray[i] + '</option>');
});

$yearDropDown.change(function () {
    var selectedyear = this.value;
    //filter based on  selected year.
    makesArray = jQuery.grep(ProductInfo, function (product, i) {
        return product.Year == selectedyear;
    });
    updateTable(makesArray);
});

//To update the table element with selected items
updateTable = function (collection) {
    $container.empty();
    for (var i = 0; i < collection.length; i++) {
        $container.append("<tr><td>" + collection[i].Year + "</td><td> " + collection[i].Make + "</td><td>" + collection[i].Model + "</td></tr>");
    }
}