Add instead of concatenating number to an input value

Asked

Viewed 391 times

2

I don’t know if I made myself clear, but in the javascript code below, I want every time I click the button, a sum occurs, but I’m only able to concatenate. Thank you!

function somar(){
    document.getElementById("valorSomado").value += 80;
}
<button onclick="somar();">Somar</button>

<input type="text" id="valorSomado">

1 answer

5


The value of the input is read as String, you have to convert into Number to add instead of concatenate.

You can do it like this:

var somar = (function(el) {
    return function() {
        el.value = Number(el.value) + 80;
    }
})(document.getElementById("valorSomado"));

jsFiddle: https://jsfiddle.net/co29oovs/

or using global space:

var somado = document.getElementById("valorSomado");
function somar() {
    somado.value = Number(somado.value) + 80;
}
  • 1

    It worked, thank you very much!

  • A cool tip is to use typeof to check the variable type.

  • 1

    @Mauroalexandre In this case do not need, because the value field will always be string.

  • @Freneticfx great! If you want you can click and mark the answer as "accept".

Browser other questions tagged

You are not signed in. Login or sign up in order to post.