Reputation: 841
I am trying to create a stamp duty calculator.
Currently, I have an array of objects containing 3 properties, every object has the same property name but different values.
I am trying to loop through this array to append property 1 and 2 to a table row if a button is clicked, however the loop appends only the first object properties and not the others.
I know there have been similar queries but none of them have helped. I'm sure there is something simple I am missing.
I have also attached an img for a better understanding of the problem
here is my code
var taxbands = [
{
min: 0,
max: 125000,
percent: 0
},
{
min: 125000,
max: 250000,
percent: 0.02
},
{
min: 250000,
max: 925000,
percent: 0.05
},
{
min: 925000,
max: 1500000,
percent: 0.1
},
{
min: 1500000,
max: null,
percent: 0.12
}
]
var tableRow = "<tr><td>{taxband}</td><td>{percent}</td><td>{taxable}</td><td>{TAX}</td></tr>";
$('#calculate').on('click', function calculateButton() {
calculateStampDuty();
})
function calculateStampDuty() {
var userInput = parseInt($("#input-value").val());
for (i = 0; i < taxbands.length; i++) {
if (userInput < 125000) {
tableRow = tableRow.replace("{taxband}", taxbands[i].min + "-" + taxbands[i].max);
$("#explained-table").append(tableRow);
}
}
}
Upvotes: 3
Views: 107
Reputation: 4845
that's because you assign the replaced value of "tableRow" back to "tableRow". After the first iteration, tableRow doesn't contain "{taxband}" anymore, and replace has no effect.
tableRow = tableRow.replace("{taxband}", taxbands[i].min + "-" + taxbands[i].max);
$("#explained-table").append(tableRow);
You should instead add an intermediate variable:
var myRow = tableRow.replace("{taxband}", taxbands[i].min + "-" + taxbands[i].max);
$("#explained-table").append(myRow );
Upvotes: 5