Editing with recalculation in a shopping calculator in JavaScript
Let's now improve the allowEdit
function
so that the recalculation described in the
previous lesson is performed.
At this point, your function code should look something like this:
function allowEdit(td) {
td.addEventListener('dblclick', function() {
let text = td.textContent
td.textContent = '';
let input = document.createElement('input');
input.value = text;
input.focus();
td.appendChild(input);
input.addEventListener('keydown', function(event) {
if (event.key == 'Enter') {
td.textContent = this.value;
}
});
});
}
Let's add a code that will perform recalculation for the cell with the price and for the cell with the amount:
function allowEdit(td) {
td.addEventListener('dblclick', function() {
let text = td.textContent
td.textContent = '';
let input = document.createElement('input');
input.value = text;
input.focus();
td.appendChild(input);
input.addEventListener('keydown', function(event) {
if (event.key == 'Enter') {
td.textContent = this.value;
if (td.classList.contains('price') || td.classList.contains('amount')) {
// perform recalculation
}
}
});
});
}
Add the missing part of the code so that when
you change the cell with the price or the cell
with the amount, the purchase cost in the
cost
column changes, and the total
amount is also recalculated.