-1

I'm still new using Javascript I have some problem with calculation using javascript right now. The problem is it won't count.

Let me know which one I made mistake and how to solve it. I'm really sorry because this is my first time using javascript.

<script text="javascript">
    var p = 0;
    var b = 0;
    var c = 0;
    function calc() {
      var p = document.getElementById("pokok").value;
      var b = document.getElementById('bonus').value;
      var c = document.getElementById('cut').value;

        if (p == 'pokok') { }
        total = p + b - c;

        document.getElementById("total").value=total;
    }
</script>

What I want to do from my code is

P + B - C = total

so basically 10 + 10 - 5 = 15

Kamil Kiełczewski
  • 85,173
  • 29
  • 368
  • 345
Skyest
  • 33
  • 1
  • 5

2 Answers2

2

A few points:

  1. document.getElementById(<string id>).value returns a string. Using + on two string objects performs a concatenation of the two.

  2. You've forgotten to close your function declaration with a }.

  3. You've arbitrarily declared p, b, and c in two completely separate contexts.

  4. You have an if statement if (p == "pokok") {} that doesn't actually do anything.

(Since you haven't included your relevant HTML, I've taken the liberty of creating some for demonstration purposes.)

The solution specific to your question is to parse the inputs' values as integers using parseInt() before attempting to add them:

function calc() {
  var p = parseInt(document.getElementById("pokok").value);
  var b = parseInt(document.getElementById('bonus').value);
  var c = parseInt(document.getElementById('cut').value);

  total = p + b - c;

  document.getElementById("total").value = total;
}
<input type="text" id="pokok" placeholder="pokok" />
<input type="text" id="bonus" placeholder="bonus" />
<input type="text" id="cut" placeholder="cut" />
<button onclick="calc()">Calculate</button>

<input type="text" id="total" placeholder="total" disabled="disabled" />
esqew
  • 42,425
  • 27
  • 92
  • 132
  • Hello, Thanks a lot for the solution. I really appreciate it for you to help me with this problem. – Skyest Aug 15 '19 at 07:38
0

Use '+' before each value to cast string to number

function calc() {
  total.value = +pokok.value + +bonus.value - +cut.value
}

function calc() {
  total.value = +pokok.value + +bonus.value - +cut.value
}
<input type="text" id="pokok" placeholder="pokok" />
<input type="text" id="bonus" placeholder="bonus" />
<input type="text" id="cut" placeholder="cut" />
<button onclick="calc()">Calculate</button>

<input type="text" id="total" placeholder="total" disabled="disabled" />
Kamil Kiełczewski
  • 85,173
  • 29
  • 368
  • 345