1

Maybe a dumb question but i am trying to grab a number that is in a textbox and add 1 to it by pressing a button.

Here is the html

<input type="text" id="txt_invoer" value="1">
<button onclick="countUp()">+</button>
<button onclick="countDown()">-</button>

Here is the javascript

<script>
    function countUp() {
        var i = parseInt(document.getElementById('txt_invoer').value);
        var iResult = i++;
        document.getElementById('txt_invoer').innerHTML = 
        iResult.toString();
    }
</script>

I hope im not being too dumb... Thanks in advance

Jasper Simons
  • 21
  • 1
  • 3

2 Answers2

1

Welcome to stackoverflow buddy!

Just use the DOM element's .value field to update an input's value. innerHTML could be used to update a div's content or such.

Also i++ increments the value but returns the value of i before being incremented, so you should be using ++i to return the incremented value.

function countUp() {
    var txtInvoer = document.getElementById('txt_invoer');
    var i = parseInt(txtInvoer.value, 10);
    txtInvoer.value = ++i;
}
<input type="text" id="txt_invoer" value="1">
<button onclick="countUp()">+</button>
<button onclick="countDown()">-</button>
Bamieh
  • 10,358
  • 4
  • 31
  • 52
1

When doing i++; the assignment of value is done before increment. So that's why a lot of people is using ++i. Where assignment is done after increment.

I suggest you to solutions :

  • ++i;
  • i += 1; // short method of i = i + 1;

I mostly recommend the second. A lot of people doesn't know this, so i didn't encourage to use ++ to disable any risk of mistake.

Have a look here for Mozilla documentation about ++ : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators#Increment_()

MathKimRobin
  • 1,268
  • 3
  • 21
  • 52
  • 1+, what you are saying is also encouraged by airbnb's javascirpt guide: https://github.com/airbnb/javascript#variables--unary-increment-decrement – Bamieh Dec 22 '17 at 13:18
  • Yeah I didn't included it, but you're true. It's encouraged by a lot of big companies. – MathKimRobin Dec 22 '17 at 13:25