-1

Something that has bugged me for a while and always giving me headaches.

I have an input field with a value in numbers

<input id="base-life" class="base-stats" type="number" name="base-life" value="20" readonly />

I am picking up the value of the input field with

let charlife = document.getElementById('base-life');

I have a number with which i want to increase the value of the base-life input field. This of course changes dynamically based on other stuff but let's say it's 2

let increaseWith = 2;

in an onclick function i want to increase base-life with 2 (base-life + 2) everything it is clicked

function increase() {
    charlife.value += increaseWith;
}

Now this only adds 2 to the value of the input field, makes it 202. I know that this happens when one of the numbers are actually strings. Perhaps my charlife. I tried everything and it gets worse. I tried parseInt(charlife.value) - no luck. I tried other methods but it doesn't work. And i only have this problem with input fields. When the element is just a or another simpler html element - it all works easier. Has to do with how JS parses input fields. Can someone shed some light?

isherwood
  • 58,414
  • 16
  • 114
  • 157
Djongov
  • 195
  • 2
  • 13

2 Answers2

2

let charlife = document.getElementById('base-life');
let increaseWith = 2;
function increase() {
     value = parseInt(charlife.value);
     value += increaseWith;
     charlife.value = value;
}
<input id="base-life" class="base-stats" type="number" name="base-life" value="20" readonly />
<button onclick="increase()">Increase</button>
Tiffany
  • 487
  • 2
  • 13
1

Here is the working snippet with some custom code that is according to your specifications

<input id="base-life" class="base-stats" type="number" name="base-life" value="20" readonly />
<button class="add" onclick="let increaseWith = 2;document.getElementById('base-life').value = parseInt(document.getElementById('base-life').value)+increaseWith;">add</button>
Onkar
  • 2,409
  • 2
  • 11
  • 14
  • Ok so parseInt was still the way to go for me but i just can't use += like i though i can. Thanks for this. Tiffany's approach is with += but using additional variable. I am a bit torn on which approach is better. – Djongov Jan 04 '21 at 20:21
  • There is an assignment to value also in a single line, so we can't use `+=` using `parseInt` along with it. we need to assign the expression to a variable and then assign that variable to the value of input @Tiffany did already – Onkar Jan 05 '21 at 03:01