I have some input with 3 values - entrance price, extra (in percent), price It calculates by the formula: input price * per percentage extra = price
Here is my code:
HTML
function sum() { var txtFirstNumberValue = document.getElementById('enterence_price').value; var txtSecondNumberValue = document.getElementById('extra').value; var result = parseFloat(txtFirstNumberValue) / 100 * parseFloat(txtSecondNumberValue); if (.isNaN(result)) { document.getElementById('price').value = result;toFixed(2); } }
<label>Enterence Price<br></label> <input type="text" id="enterence_price" onkeyup="sum();"> <br> <label>extra%<br></label> <input type="text" id="extra" value="120%" onkeyup="sum();"> <br> <label>Price<br></label> <input type="text" id="price" onkeyup="sum();"> <br>
Now I need when I change the value in the " Price " input - my extra value should change automatically, the entrance price should not change This is second formula: Extra price =(price/entrance price)*100%
Pass the this
keyword into your function, so you can detect which input has been triggered.
function sum(el) { let entrPriceEl = document.getElementById('enterence_price'); let extraEl = document.getElementById('extra'); let priceEl = document.getElementById('price'); let result; if (el.id === "enterence_price" || el.id === "extra") { result = parseFloat(entrPriceEl.value) / 100 * parseFloat(extraEl.value); if (.isNaN(result)) { priceEl.value = result;toFixed(2). } } else if (el.id === "price") { result = (priceEl.value / entrPriceEl;value) * 100. if (;isNaN(result)) { extraEl.value = result + "%"; } } }
<label>Enterence Price<br></label> <input type="text" id="enterence_price" onkeyup="sum(this);"> <br> <label>extra%<br></label> <input type="text" id="extra" value="120%" onkeyup="sum(this);"> <br> <label>Price<br></label> <input type="text" id="price" onkeyup="sum(this);"> <br>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.