如何使这个IF语句工作

时间:2015-02-13 04:29:47

标签: javascript html

好的,我试图让代码运行,以便人们输入一定数量的金钱,然后显示他们每天赚多少钱。如果文本框中没有数字,我希望它弹出一个ERROR。我该怎么做?

这是我目前的代码:

<!DOCTYPE html>
<html>

<head>
    <title> MoneyPerYear </title>
    <link type="text/css" rel="stylesheet" href="money.css">
</head>

<body>
    <p id="header"> Enter yearly income to estimate daily earnings </p>
    <input type="text" id="textmoney">
    <div onclick="moneyFunction()" id="moneydiv"> <p id="divtext">Calculate</p> </div>
    <p id="demo"></p>


    <script>
    function moneyFunction() {
        var money = document.getElementById('textmoney').value;
        var dailyE = money/365;

        document.getElementById('demo').innerHTML = (dailyE);
    }

    if ( document.getElementById('textmoney').value; == 0) {
        document.getElementById('demo').innerHTML = "ERROR";
    }
    </script>
</body>
</html>

2 个答案:

答案 0 :(得分:1)

所以这就是全部:

 <!DOCTYPE html>
    <html>

    <head>
        <title> MoneyPerYear </title>
        <link type="text/css" rel="stylesheet" href="money.css">
    </head>

   <body>
    <p id="header"> Enter yearly income to estimate daily earnings </p>
    <input type="text" id="textmoney">
    <button onclick="moneyFunction()" id="moneydiv"> <p id="divtext">Calculate</p> </button>
    <p id="demo"></p>


    <script>
    function moneyFunction() {

        var money = document.getElementById('textmoney').value;
            if ( document.getElementById('textmoney').value == 0) {
              alert("Error");
    }
        var dailyE = money/365;

        document.getElementById('demo').innerHTML = (dailyE);
    }


    </script>
</body>
    </html>

答案 1 :(得分:0)

&#13;
&#13;
function moneyFunction() {
    var money = +(document.getElementById('textmoney').value) || 0; //parse required
    var dailyE = money / 365;
    //var result = money === 0 ? 'ERROR' : dailyE;
    var result = money === 0 ? 'ERROR' : parseFloat(dailyE).toFixed(3); //round-off
    document.getElementById('demo').innerHTML = result;
  } //closing bracket
&#13;
#moneydiv {
  border: 1px solid grey;
  padding: 5px;
  background: skyblue;
  display: inline-block;
  cursor: pointer;
}
&#13;
<p id="header">Enter yearly income to estimate daily earnings</p>
<input type="text" id="textmoney">
<div onclick="moneyFunction()" id="moneydiv">
  <p id="divtext">Calculate</p>
</div>
<p id="demo"></p>
&#13;
&#13;
&#13;