本文介绍了使用单选按钮在javascript中编写代码并使用if else循环来计算简单和/或复合兴趣的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我被要求用javascript编写代码,根据输入数据在输出框中显示结果。
我已写下以下代码。但无论我选择哪个单选按钮(简单兴趣或复合兴趣),程序始终计算复合兴趣并相应地显示结果。哪里出错了,有人可以提出建议。在此先感谢。
我尝试过:
I have been asked to write a code in javascript to show the results in the output boxes based on the input data.
I have written down the following code. However regardless of which radio buttons (Simple Interest or Compound Interest) I select, the program always calculates compound interest and displays the results accordingly. Where am I going wrong, could someone please advise. Thanks in advance.
What I have tried:
function calc() {
var p = document.getElementById("p").value;
var r = document.getElementById("r").value;
var t = document.getElementById("t").value;
var int = document.getElementById.value;
if (int == "si") {
var sip = (p \* r \* t) / 100
var ta = p + sip
document.getElementById("i").value = sip;
document.getElementById("a").value = ta;
} else {
var cta = p\*(Math.pow((1+r/100),t))
var cmp = cta-p
document.getElementById("i").value = cmp;
document.getElementById("a").value = cta;
}
}
<h1> Interest Calculator </h1>
Principal =
<br><br><br>
Rate of Interest =
<br><br><br>
Time (in years) =
<br><br>
<h1> Interest Type </h1>
Simple Interest
\ \ \
Compound Interest
<br><br>
<hr noshade="">
Interest
<br><br>
Amount
<br><br>
\ \ \
推荐答案
var int = document.getElementById.value;
这一行缺少一些东西,在 Id
和 .value
之间。
<!DOCTYPE html>
<html>
<head>
<script>
function calc() {
p = document.getElementById("p").value;
r = document.getElementById("r").value;
t = document.getElementById("t").value;
var int = document.getElementsByName("int").value;
if (document.f.int[0].checked == true) {
sip = (p * r * t) / 100;
ta = (p*1 + sip*1);
document.getElementById("i").value = sip;
document.getElementById("a").value = ta;
}
else if (document.f.int[1].checked == true) {
cta = p*(Math.pow((1+r/100),t));
cmp = (cta*1-p*1);
document.getElementById("i").value = cmp;
document.getElementById("a").value = cta;
}
}
</script>
</head>
<body>
<form name = "f">
<h1> Interest Calculator </h1>
Principal = <input type = "text" id = "p" autofocus>
<br><br><br>
Rate of Interest = <input type = "text" id = "r">
<br><br><br>
Time (in years) = <input type = "text" id = "t">
<br><br>
<h1> Interest Type </h1>
<input type = "radio" name = "int" value = "si"> Simple Interest
<input type = "radio" name = "int" value = "ci"> Compound Interest
<br><br>
<hr noshade>
Interest <input type = "text" id = "i">
<br><br>
Amount <input type = "text" id = "a">
<br><br>
<input type = "button" name = "cal" value = "Calculate" onclick = "calc()">
<input type = "reset" value = "Reset">
</form>
</body>
</html>
这篇关于使用单选按钮在javascript中编写代码并使用if else循环来计算简单和/或复合兴趣的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!