jQuery Filter JSON Data
HTML
<div id="DrpDwn">
Year:<select id="DropDown_Year"><option>Year</option></select>
Make:<select id="DropDown_Make"><option>None</option></select>
</div>
<br />
Filtered product information
<table id="details" border="1" cellpadding="2" cellspacing="2">
<thead>
<tr>
<th >Year</th>
<th>Make</th>
<th>Model</th>
</tr>
</thead>
<tbody></tbody>
</table>
CSS
th,td
{
width:100px;
}
JavaScript
{
"suraj":
{
"Year" : 2011,
"Make ": "Product 1",
"Model": "101"
},
}
var yearsArray = [];
var makesArray = [];
// adding unique years to yearsArray
$.each(ProductInfo, function (index)
{
var year = Year;
console.log(year);
if ($.inArray(year, yearsArray) == -1) {
yearsArray.push(year);
}
});
//sorting the year
yearsArray.sort();
var $yearDropDown = $("#DropDown_Year");
var $makeDropDown = $("#DropDown_Make");
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;
console.log(selectedyear);
//filter based on selected year.
makesArray = jQuery.grep(ProductInfo, function (product, i) {
return product.Year == selectedyear;
});
$makeDropDown.empty();
$makeDropDown.append('<option>None</option>');
for (var i = 0; i < makesArray.length; i++) {
$makeDropDown.append('<option value="' + makesArray[i].Make + '">' + makesArray[i].Make + '</option>');
}
updateTable(makesArray);
});
$makeDropDown.change(function () {
var selectedMake = this.value;
//filter select based on selected Make
selectedArray = jQuery.grep(ProductInfo, function (product, i) {
return product.Make == selectedMake;
});
updateTable(selectedArray);
});
//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>");
}
}