I'm building a simple multiplication form which calculates a sum and renders the answer direct to the DOM. I'm using a <select>
menu to choose the initial number and an <input type="number">
for the multiplier.
Is it possible to recalculate the answer and render it to the DOM automatically when changing the <select>
value? The form currently works but the user will need to delete the multiplier after re-selecting the initial number.
Here's where I currently am:
const selectValIn = document.querySelector(".select-val-in");
const inputValIn = document.querySelector(".input-val-in");
const valOut = document.querySelector(".val-out");
let multiplier = 2;
selectValIn.addEventListener("change", switchValIn);
inputValIn.addEventListener("keyup", convert);
function switchValIn() {
let selectedVal = selectValIn.value;
if (selectedVal === "four") {
multiplier = 4;
} else if (selectedVal === "six") {
multiplier = 6;
} else if (selectedVal === "eight") {
multiplier = 8;
}
}
function convert(e) {
const inputValIn = e.target.value;
const multiplication = inputValIn * multiplier;
valOut.innerText = multiplication;
}
<div class="converter">
<div class="converter-row">
<select class="select-val-in">
<option value="two">2</option>
<option value="four">4</option>
<option value="six">6</option>
<option value="eight">8</option>
</select>
</div>
<div class="converter-row">
<label>Multiplied by:</label>
<input class="input-val-in" type="number" value="0" />
</div>
<div class="converter-row">
<p>Equals: <span class="val-out">0</span></p>
</div>
</div>
Here's a Codepen with a working example: https://codepen.io/abbasarezoo/pen/59776227c017d1c1a3a245a37c305e76