JSFiddle - React, Tailwind, and code Playground
HTML
<h1>
Price calculator
</h1>
<div id="dimensions-holder" class="container">
<div id="template" class="container dimensions">
<input type="text" class="input-numbers" placeholder="width" />
<span class="sign">×</span>
<input type="text" class="input-numbers" placeholder="height" />
<span class="sign">=</span>
<span class="result">0</span>
</div>
</div>
<div class="misc">
<span>Total: </span><span id="total">0</span>
</div>
<div class="misc">
<button id="add-row">Add row</button>
</div>
CSS
.sign {
margin: 2px;
}
.input-numbers {
width: 50px;
margin: 2px;
}
.container {
border: solid 1px black;
}
.dimensions {
padding: 2px;
margin: 2px;
}
.misc {
padding: 4px;
}
#add-row {
width: 100px;
height: 30px;
}
JavaScript
$(function() {
// Handler for input type=text change event
function inputChangedVal() {
/* ===========================
* Compute product for current
* set of dimensions
*/
// Cast value to Number and reassign
var val = Number($(this).val());
$(this).val(val);
// Initialize prod too current value
var prod = val;
// Find all other textboxes and iterate over them
// an multiply their value to get final prod
$(this).siblings('input[type="text"].input-numbers').each(function() {
prod *= $(this).val();
});
// Display value in span
$(this).siblings('span.result').text(prod);
/* =============================
* Compute total sum of products
*/
// Initialize sum
var sum = 0;
// Find all product spans, iterate over
// them and add their value to sum
$('span.result').each(function() {
sum += Number($(this).text());
});
// Display value
$('#total').text(sum);
}
// Attach handler to initial box
$('input[type="text"].input-numbers').change(inputChangedVal);
// save a template reference and remove id
var template = $('#template.container.dimensions').attr('id', null).clone();
// Handle adding row
$('#add-row').click(function() {
// Clone template
var elem = template.clone();
// Find all input type=text and add change event handler
elem.children('input[type="text"].input-numbers')
.change(inputChangedVal);
// Append row
$('#dimensions-holder.container').append(elem);
});
});