我希望输入只有数字,如果有其他任何东西,那么它会提醒你输入一个字母,它必须是一个不同的功能。此外,它必须在vanilla javascript中,它适用于一个项目,并且必须具有3个运行功能,这就是为什么它必须在一个单独的函数中。谢谢!
<!doctype html>
<html>
<head>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css" integrity="sha384-9gVQ4dYFwwWSjIDZnLEWnxCjeSWFphJiwGPXr1jddIhOegiu1FwO5qRGvFXOdJZ4" crossorigin="anonymous">
<link href="https://fonts.googleapis.com/css?family=Raleway" rel="stylesheet">
<meta charset="utf-8">
<title>Tip Calc.</title>
<style>
html,body{
width:100%;
height:100%;
}
body{
margin:0px;
overflow-x:hidden;
background-color: #f9f8f4 !important
}
p{
font-size: 18px !important;
font-family: 'Raleway', sans-serif;
}
h1,h2,h3{
font-family: 'Raleway', sans-serif;
}
</style>
</head>
<body>
<div class="container">
<br>
<h1 class="text-center">Tip Calculator</h1>
<br><br>
<div class="row">
<div class="col-lg-6">
<form>
<div class="form-group">
<label for="exampleInputEmail1">Total</label>
<input type="text" class="form-control" id="total" aria-describedby="emailHelp" placeholder="Enter Total Price">
</div>
<div class="form-group">
<label for="exampleInputPassword1">Tip Percentage %</label>
<input type="text" class="form-control" id="percent" placeholder="Tip Percentage">
</div>
<button type="submit" class="btn btn-primary" id="btn">Submit</button>
</form>
</div>
<div class="col-lg-6">
<h2>Total Price:</h2><h3 id="totalprice"></h3>
</div>
</div>
</div>
<script>
window.addEventListener("DOMContentLoaded",init,false);
function init(){
document.getElementById("btn").addEventListener("click", getprice, false);
}//end init function
function getprice(e) {
e.preventDefault();
math();
// var totalpriceout = document.getElementById("totalprice").value = totalValue.toFixed(2);
}
function math(){
var numVal1 = Number(document.getElementById("total").value);
var numVal2 = Number(document.getElementById("percent").value) / 100;
var totalValue = numVal1 + (numVal1 * numVal2)
document.getElementById("totalprice").innerHTML = "$" + totalValue.toFixed(2);
}
</script>
</body>
</html>
答案 0 :(得分:0)
您正在寻找的基线是parseFloat
,即
var foo = "abcdef"
var bar = "123456"
foo == parseFloat(foo)
->false
bar == parseFloat(bar)
->true
因为这似乎是homework help我不想放弃太多。
答案 1 :(得分:0)
如上所述:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseFloat,parseFloat将返回从给定值解析的浮点数。如果该值无法转换为数字,则返回NaN。
考虑结合使用Number.isNaN()。
也许: if(Number.isNaN(parseFloat(foo))){//错误处理程序} else {//常规操作} -