2 回答
TA贡献1876条经验 获得超6个赞
你正在混合jQuery在一起,JS理想情况下坚持使用一个以避免混淆。您不需要单独的函数添加第三个输入值乘以的second值。
您可以在API调用函数中执行所有这些操作。除了获得你还需要在第三个输入上decimals使用。toFixed()finalamount
此外,为了获得更好的用户体验,我建议使用更好的.on功能,因为你有类型号。您可以通过单击增加输入来使用您的数字,新值和总数将立即反映出来,而不是再次单击或输入。inputkey-upinputincrement
现场工作演示:
$("#validationTooltip02").on('input', function() { //input[name='calc']
let convFrom;
if ($(this).prop("name") == "btc") {
convFrom = "btc";
convTo = "usd";
} else {
convFrom = "usd";
convTo = "btc";
}
$.getJSON("https://api.coindesk.com/v1/bpi/currentprice/usd.json",
function(data) {
var origAmount = parseFloat($("input[name='" + convFrom + "']").val());
var exchangeRate = parseInt(data.bpi.USD.rate_float);
let amount;
if (convFrom == "btc")
amount = parseFloat(origAmount * exchangeRate);
else
amount = parseFloat(origAmount / exchangeRate);
$("input[name='" + convTo + "']").val(amount.toFixed(2));
//Add here
var a = parseFloat($('#a').val())
var b = parseFloat($('#b').val())
var final = a * b//final amount multiplied by 465
$('#c').val(final.toFixed(2))
});
});
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://stacksnippets.net/scripts/snippet-javascript-console.min.js?v=1"></script>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<form>
<input type="number" name="btc" class="form-control" id="validationTooltip02" placeholder="BTC">
<input type="number" name="usd" class="form-control" id="a" placeholder="USD" readonly>
<input type="hidden" id="b" value="465">
<input name="amount" class="form-control" type="text" placeholder="0.00000" id="c" aria-label="0.00000" readonly>
</form>
TA贡献2036条经验 获得超8个赞
所以,我认为你应该在你已经调用.form-controlkeyup 的函数中使用你的 add 函数,如下所示:
$(".form-control").keyup(function() { //input[name='calc']
let convFrom;
if ($(this).prop("name") == "btc") {
convFrom = "btc";
convTo = "usd";
} else {
convFrom = "usd";
convTo = "btc";
}
$.getJSON("https://api.coindesk.com/v1/bpi/currentprice/usd.json",
function(data) {
var origAmount = parseFloat($("input[name='" + convFrom + "']").val());
var exchangeRate = parseInt(data.bpi.USD.rate_float);
let amount;
if (convFrom == "btc")
amount = parseFloat(origAmount * exchangeRate);
else
amount = parseFloat(origAmount / exchangeRate);
$("input[name='" + convTo + "']").val(amount.toFixed(2));
// Here goes the content of the add function
var x = parseInt(document.getElementById("a").value);
var y = parseInt(document.getElementById("b").value)
document.getElementById("c").value = x * y;
});
});
添加回答
举报