如何解决使用js更改单选按钮时更改单选按钮的值和id
在这里,我希望用户根据自己的选择更改单选按钮,并希望更改单选按钮的值和 ID 以计算总值。 现在我检查了默认的单选输入,它适用于此,我需要它适用于单选按钮的更改。
const profit = document.querySelector('input[name="rdmonths"]:checked').value;
const id = document.querySelector('input[name="rdmonths"]:checked').id;
const principal = 10000;
const time = id;
const rate = profit/100;
const n = 1;
const compoundInterest = (p,t,r,n) => {
const amount = p * (Math.pow((1 + (r / n)),t));
return amount;
};
document.getElementById("total-amount").innerHTML = (compoundInterest(principal,time,rate,n));
<input id="1" type="radio" class="months" value="8" checked="checked" name="rdmonths"/><span>12</span>
<input id="2" type="radio" class="months" value="8" name="rdmonths"/><span>24</span>
<input id="3" type="radio" class="months" value="8" name="rdmonths"/><span>36</span>
<input id="4" type="radio" class="months" value="8" name="rdmonths"/><span>48</span>
<input id="5" type="radio" class="months" value="8" name="rdmonths"/><span>60</span>
<div style="float:right; width:45%; margin-bottom:50px;">
<h2><b>Representative</b></h2>
<p>Total Amount:<span id="total-amount" style="margin-left:30px;"></span></p>
</div>
解决方法
如果您为 click
组的每个成员分配一个 radio
事件处理程序,您可以对每个特定选项应用相同的逻辑。如果此逻辑位于函数内,则可以更轻松地调用后续 clicks
// apply the logic within a reusable function
const calculate_compount_interest=function(){
const profit = document.querySelector('input[name="rdmonths"]:checked').value;
const id = document.querySelector('input[name="rdmonths"]:checked').id;
const principal = 10000;
const time = id;
const rate = profit/100;
const n = 1;
const compoundInterest = (p,t,r,n) => {
const amount = p * (Math.pow((1 + (r / n)),t));
return amount.toFixed(2); // limit the result to a meaningful precision
};
document.getElementById("total-amount").innerHTML = (compoundInterest(principal,time,rate,n));
}
document.addEventListener('DOMContentLoaded',()=>{
// assign listener to each radio button
document.querySelectorAll('input[type="radio"][name="rdmonths"]').forEach( input=>{
input.addEventListener('click',calculate_compount_interest )
})
// call on initial page-load
calculate_compount_interest();
})
<input id="1" type="radio" class="months" value="8" checked="checked" name="rdmonths"/><span>12</span>
<input id="2" type="radio" class="months" value="8" name="rdmonths"/><span>24</span>
<input id="3" type="radio" class="months" value="8" name="rdmonths"/><span>36</span>
<input id="4" type="radio" class="months" value="8" name="rdmonths"/><span>48</span>
<input id="5" type="radio" class="months" value="8" name="rdmonths"/><span>60</span>
<div style="float:right; width:45%; margin-bottom:50px;">
<h2><b>Representative</b></h2>
<p>Total Amount:<span id="total-amount" style="margin-left:30px;"></span></p>
</div>
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。