Home > Software engineering >  How can I increase value of an input field?
How can I increase value of an input field?

Time:02-10

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"  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?

CodePudding user response:

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

CodePudding user response:

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

<input id="base-life"  type="number" name="base-life" value="20" readonly />
<button  onclick="let increaseWith = 2;document.getElementById('base-life').value = parseInt(document.getElementById('base-life').value) increaseWith;">add</button>

  •  Tags:  
  • Related