我创建了一个包含三个字段的HTML表单。字段A用于输入文本,字段B和C用于数字输入。
我创建了一个函数来计算B i C,并将A,B和C中的数据输出到页面上。
如何做到这一点,以便必须填写字段A,字段B和C必须为正值?
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Tax calculator</title>
<meta charset="UTF-8">
</head>
<body>
<div>
Field A:<input id="name" type="text">
Field B:<input id="tBas" type="value">
Field C:<input id="tRat" type="value">
<button id="calc">Calculate !</button>
</div>
<strong>
<div id="name"> </div>
<div id="income"> </div>
<div id="rate"> </div>
<div id="result"> </div>
</strong>
<script src="testCalculate.js">
</script>
</body>
</html>
JavaScript:
function calculate() {
var name = document.getElementById('name').value;
var base = parseFloat(document.getElementById('tBas').value);
var rate = document.getElementById('tRat').value;
var taxPayer = ("First and last name: ") + (name);
var taxIncome = ("Income for taxation: ") + ((base).toFixed(2));
var taxRate = ("Tax rate: ") + (rate) + ("%.");
var taxToPay = ("You need to pay: ") + ((base * rate / 100).toFixed(2));
document.getElementById('name').innerHTML = taxPayer;
document.getElementById('income').innerHTML = taxIncome;
document.getElementById('rate').innerHTML = taxRate;
document.getElementById('result').innerHTML = taxToPay;
}
document.getElementById('calc').addEventListener('click', calculate);
答案 0 :(得分:0)
此技巧无需使用JS 要填充输入,请将其设置为
<input id="name" type="text" required>
然后具有正值
<input id="tBas" type="number" min=0 >
答案 1 :(得分:0)
要检查是否填写了一个字段,您可以将其值与""
进行比较。
要检查某个字段是否具有正值,可以使用parseInt
将值(字符串)转换为整数,然后将其与0 > 0
进行比较。
类似的事情应该可以解决!
function calculate() {
var name = document.getElementById('name').value;
var base = parseFloat(document.getElementById('tBas').value);
var rate = document.getElementById('tRat').value;
if (name != "" && parseInt(base) > 0 && parseInt(rate) > 0) {
var taxPayer = ("First and last name: ")+(name);
var taxIncome = ("Income for taxation: ")+((base).toFixed(2));
var taxRate = ("Tax rate: ")+(rate)+("%.");
var taxToPay = ("You need to pay: ")+((base*rate/100).toFixed(2));
document.getElementById('name').innerHTML = taxPayer;
document.getElementById('income').innerHTML = taxIncome;
document.getElementById('rate').innerHTML = taxRate;
document.getElementById('result').innerHTML = taxToPay;
}
}
document.getElementById('calc').addEventListener('click', calculate);
<!DOCTYPE html>
<html lang="en">
<head>
<title>Tax calculator</title>
<meta charset="UTF-8">
</head>
<body>
<div>
Field A:<input id="name" type="text">
Field B:<input id="tBas" type="value">
Field C:<input id="tRat" type="value">
<button id="calc">Calculate !</button>
</div>
<strong>
<div id="name"> </div>
<div id="income"> </div>
<div id="rate"> </div>
<div id="result"> </div>
</strong>
</body>
</html>
答案 2 :(得分:0)
ID应该是uniq。您应该对div#name
使用另一个ID。
例如,进入您的html代码:
<div id="div_name"> </div>
然后,进入您的脚本
document.getElementById('div_name').innerHTML= taxPayer;