I have a simple calculator that changes on input to convert US Dollars to Viet Nam Dong. It works just fine except for the fact that after a number is input and then removed via backspace, a "0.00" remains in the box that the calculation was performed in. I would like for the box to be blank when the other box is blank after removing a number.
Here is my Javascript:
function vndCalc() {
var cusd = document.getElementById("usd").value;
var cvnd = document.getElementById("vnd");
var calc = cusd * 22477.50;
cvnd.value = calc.toFixed(2);
}
function usdCalc() {
var cusd = document.getElementById("usd");
var cvnd = document.getElementById("vnd").value;
var calc = cvnd / 22477.50;
cusd.value = calc.toFixed(2);
}
Here is the HTML as well:
<fieldset id=calculator>
<legend>USD to VND Calculator</legend>
<label>US Dollars:<input type="text" id="usd" oninput="vndCalc()"/></label>
<label>VN Dongs:<input type="text" id="vnd" oninput="usdCalc()"/></label>
</fieldset>
I tried playing around with "if" functions, but I couldn't get anything to work. Please help!
You can check if the input field == "" and set the output field to be the same
From USD
cvnd.value = cusd == "" ? "" : calc.toFixed(2);
And to USD
cusd.value = cvnd == "" ? "" : calc.toFixed(2);
If you don't like the ternary form you can do
From USD
if (cusd == "") {
cvnd.value = "";
} else {
cvnd.value = calc.toFixed(2);
}
and to USD
if (cvnd == "") {
cusd.value = "";
} else {
cusd.value = calc.toFixed(2);
}
You can control the other input with a conditional. For instance, you can try this:
function usdCalc() { var cusd = document.getElementById("usd"); var cvnd = document.getElementById("vnd").value; var calc = cvnd / 22477.50; if (cvnd == ''){ cusd.value = ''; } else { cusd.value = calc.toFixed(2); } }
I would personally add 2 buttons to trigger the conversion. Jsfiddle . Example:
var exchangeRate = 22477.50,
usdSelector = $('#usd'),
vndSelector = $('#vnd');
$('#convert1').click(function(){
vndSelector.val(usdSelector.val() * exchangeRate);
})
$('#convert2').click(function(){
usdSelector.val(vndSelector.val() / exchangeRate);
})
$('#clear').click(function(){
usdSelector.val("");
vndSelector.val("");
})
And Html:
<fieldset id="calculator">
<legend>USD to VND Calculator</legend>
<label>US Dollars: <input type="text" id="usd"/></label>
<label>VN Dongs: <input type="text" id="vnd"/></label>
</br>
<button id="convert1">Convert Dollars to Dongs</button>
<button id="convert2">Convert Dongs to Dollars</button>
<button id="clear">Clear</button>
</fieldset>
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.