简体   繁体   中英

Simple time and half calculator in JavaScript

I have made a simple time and half calculator in HTML and JavaScript, but for some reason, when I click the Calculate button, the P element does not show the result.

Here is my code:

http://codepen.io/chrissylvester10/pen/wJxder

html>
    <head>
    </head>

    <body>
        <h1>Time and Half Calculator</h1>
        <input id="fare" size="7" maxlength="7" name="fare" style="width:75px" value="0" />
        <input type="button" value="Calculate" onclick="calculator()">
        <p id="result"></p>
    </body>
</html>

var fare = document.getElementById("#fare").value;

function calculator() {
    var result = fare / 2 + fare;
    document.getElementById("result").innerHTML = result;
}

Please fork it because I need to see the changes.

First thing, you don't need the # in var fare = document.getElementById("#fare").value; .

It should be var fare = document.getElementById("fare").value;

That line of code should also be inside the function, so it will read the new value every time you change it, otherwise, it will just return 0.

Lastly, you want to parse the number so it isn't misread as a string.

function calculator() {
  var fare = parseInt(document.getElementById("fare").value);
  var result = fare / 2 + fare;
  document.getElementById("result").innerHTML = result;
}

edit:

A much simpler way to do this would be

function calculator() {
  document.getElementById("result").innerHTML = document.getElementById("fare").value*1.5;
}

You are getting the value at the start and not the actual value.

Solution: Move the fare declaration inside of the function.

Small change: Get only fare as id.

 function calculator() { var fare = +document.getElementById("fare").value, result = fare / 2 + fare; document.getElementById("result").innerHTML = result; } 
 <h1>Time and Half Calculator</h1> <input id="fare" size="7" maxlength="7" name="fare" style="width:75px" value="0" /> <input type="button" value="Calculate" onclick="calculator()"> <p id="result"></p> 

What about to enclose your Javascript into <script> tags? And remove # from fare .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM