Issue
I have created 3 input fields Trade, Markup and Price. I would like for the user to enter a trade and then manipulate the price either by markup or by entering the price and the markup showing a reflection of that price.
I would like the calculation to be live and to not have to submit a button everytime to view changes.
I did split the code up into 2 separate scripts but that did not make a difference and I have also changed the addEventListeners to "change" but that still did not work. I have a felling I will need to add a IF statement between the 2 results somehow.
document.getElementById("trade").addEventListener("change", calculation);
document.getElementById("price").addEventListener("change", calculation);
document.getElementById("markup").addEventListener("change", calculation);
function calculation() {
var trade = parseFloat(document.getElementById("trade").value);
var markup = parseFloat(document.getElementById("markup").value);
var price = parseFloat(document.getElementById("price").value);
var markupresult = price / trade;
var priceresult = markup * trade;
document.getElementById("markup").value = (markupresult).toFixed(2);
document.getElementById("price").value = (priceresult).toFixed(2);
}
<div class="form-group"><label>Trade</label><input type="number" id="trade" name="trade"></div>
<div class="form-group"><label>Price</label><input type="number" id="price" name="price"></div>
<div class="form-group"><label>Markup</label><input type="number" id="markup" name="markup"></div>
Solution
Check the below snippet.
You can use a switch to change only one/vice versa.
Instead of change, you can use keyup which would provide you realtime output, (Whenever the user enter a number, the result will be calculated and shown).
document.getElementById("trade").addEventListener("change", calculation);
document.getElementById("price").addEventListener("change", calculation);
document.getElementById("markup").addEventListener("change", calculation);
function calculation(event) {
var trade = parseFloat(document.getElementById("trade").value);
var markup = parseFloat(document.getElementById("markup").value);
var price = parseFloat(document.getElementById("price").value);
var markupResult = price / trade;
var priceResult = markup * trade;
switch (event.target.getAttribute("id")) {
case "markup":
document.getElementById("price").value = priceResult.toFixed(2);
break;
case "price":
document.getElementById("markup").value = markupResult.toFixed(2);
break;
}
}
<div class="form-group">
<label>Trade</label><input type="number" id="trade" name="trade" />
</div>
<div class="form-group">
<label>Price</label><input type="number" id="price" name="price" />
</div>
<div class="form-group">
<label>Markup</label><input type="number" id="markup" name="markup" />
</div>
Answered By - Abin Thaha
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.