Zaloguj | Zarejestruj | FAQ
Anonymous

how to make JavaScript calculate this correctly?

+ Odpowiedz

Posty: 1 Strona 1 z 1


how to make JavaScript calculate this correctly?

przez DDD » N mar 12, 2017 3:20 pm

i wrote some JavaScript, but i can´t get it to calculate it right.
try to load the code below in your browser.
In the first 3 fields enter for example the numbers "20", "50" "15" and push the button.
The JavaScript is supposed to take the value from the first field and add the value from the second field and minus the value from the third field and then put the total in the fourth field.
Now it should show the result "55" in the last field (if your entered "20", "50", "15" in the 3 fields), becouse 20+50-15=55 but instead it shows 2035 (properly becouse 20+(50-15) gives 2035.
I tried also to change the "calc" variable to:
calc = income1 + income2 - expenses
calc = (income1 + income2) - expenses
calc = income1 + (income2 - expenses)
but nothing helped.
The strange thing is that when I try to do 20+50-15 in alert() it calculates it correct.

<!DOCTYPE html>
<html>
<head>
<script language="JavaScript" type="text/javascript">
function myfunction() {
income1 = document.getElementById("income1").value
income2 = document.getElementById("income2").value
expenses = document.getElementById("expenses").value
calc = income1 + income2 - expenses
document.getElementById("total").value = calc

alert(20 + 50 - 15)
}
</script>
</head>
<body>
<form>
Income: <input type="Text" id="income1"><br>
Other income: <input type="Text" id="income2"><br>
Expenses: <input type="Text" id="expenses"><br>
Total: <input type="Text" value="total" id="total"><br>
<input type="button" value="Calculate" onClick="myfunction()">
</form>
</body>
</html>
Avatar użytkownika

DDD

  • Posty: 2
  • Dołączył(a): So maja 18, 2013 12:28 pm


+ Odpowiedz

Strona 1 z 1