I'm building a property valuation form.
U can filter by postcode and type.
after filtering, I should show a list with the properties and the average price but I don't know why the sum is not working.
Thank you in advance for your help :)
here my code
.................................
...
...
...
...
...
...
...
...
var houses = [{
Postcode: "2011",
Type: "typehouse1",
Price: "101"
},
{
Postcode: "2011",
Type: "typehouse1",
Price: "200"
},
{
Postcode: "2010",
Type: "typehouse1",
Price: "234"
},
{
Postcode: "2011",
Type: "typehouse1",
Price: "100"
},
{
Postcode: "2012",
Type: "typehouse2",
Price: "500"
},
{
Postcode: "2011",
Type: "typehouse2",
Price: "100"
},
{
Postcode: "2013",
Type: "typehouse2",
Price: "100"
},
{
Postcode: "2013",
Type: "typehouse2",
Price: "455"
}];
var postcodeArray = [];
var typeArray = [];
// adding unique years to yearsArray
$.each(houses, function (index) {
var postcode = houses[index].Postcode;
if ($.inArray(postcode, postcodeArray) == -1) {
postcodeArray.push(postcode);
}
});
//sorting by postcode
postcodeArray.sort();
var $pcode = $("#postcode");
var $housetype = $("#type");
var $container = $("#details").find("tbody");
// append the years to select
$.each(postcodeArray, function (i) {
$pcode.append('<option value="' + postcodeArray[i] + '">' + postcodeArray[i] + '</option>');
});
$pcode.change(function () {
var selectedpcode = this.value;
//filter based on selected postcode.
typeArray = jQuery.grep(houses, function (product, i) {
return product.Postcode == selectedpcode;
});
updateTable(typeArray);
});
$housetype.change(function () {
var selectedtype = this.value;
//filter select based on selected type
selectedArray = jQuery.grep(typeArray, function (product, i) {
return product.Type == selectedtype;
});
updateTable(selectedArray);
var sum = 0;
$(selectedArray).each(function() {
sum += $(this)[0].Price;
console.log("Added: ", $(this)[0].Price)
});
console.log("Sum is:", sum);
console.log("The average is:", sum / selectedArray.length)
});
//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].Postcode + "</td><td> " + collection[i].Type + "</td><td>" + collection[i].Price + "</td></tr>");
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<div id="DrpDwn">
Postoce<input id="postcode"></input>
House type:<select id="type">
<option>None</option>
<option value="typehouse1">type house 1</option>
<option value="typehouse2">type house 2</option>
</select>
</div>
<br />
Filtered houses information
<table id="details" border="1" cellpadding="2" cellspacing="2">
<thead>
<tr>
<th>Postcode</th>
<th>Type</th>
<th>Price</th>
</tr>
</thead>
<tbody></tbody>
</table>