Add instead of concatenating number to the value of an input

2

I do not know if I understand, but in the javascript code below, I want every time I click the button, a sum occurs, but I can only concatenate. Thanks!

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

<input type="text" id="valorSomado">
    
asked by anonymous 29.10.2016 / 19:17

1 answer

5

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

You can do this:

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

jsFiddle: link

or by using global space:

var somado = document.getElementById("valorSomado");
function somar() {
    somado.value = Number(somado.value) + 80;
}
    
29.10.2016 / 19:31