1

here's the code I'm struggling with. I'd like to concat the two inputs together and keep the result as an integer (number in JS's case).

var secsVal = -1;
function valueAssign(i) {

    if (secsVal == -1){

        document.getElementById("countdown").value = i;
        document.getElementById("countdown").innerHTML = (i);

        secsVal = i;
    }
    else {      
        secsVal = "" + secsVal + i;//concatenating first value of i to the second.
        secsVal = secsVal.map(Number);//trying to convert back to num, but I think map() needs to see an array, which I don't think I got here.

        document.getElementById("countdown").value = secsVal;
        document.getElementById("countdown").innerHTML = (secsVal);//I want to replace the first displayed digit here, with the new (concatenated) number.
    }
}
Rumen Hristov
  • 867
  • 2
  • 13
  • 29

5 Answers5

2

It makes no sense to use a number for a value in an input tag. The type is always a string.

To convert to number use either Number or an unary +

secsVal = Number(secsVal);

or

secsVal = +secsVal;
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
1

Try this

secsVal = +("" + secsVal + i);
Niyoko
  • 7,512
  • 4
  • 32
  • 59
0
secsVal = Number('' + secsVal + i)   // explicit cast to number
secsVal = +('' + secsVal + i)        // implicit cast to number
secsVal = parseInt('' + secsVal + i) // explicit cast to integer
secsVal = ~~('' + secsVal + i)       // implicit cast to integer
felixfbecker
  • 2,273
  • 1
  • 19
  • 24
0

Simply use +secsVal

var secsVal = -1;
function valueAssign(i) {

    if (secsVal == -1){

        document.getElementById("countdown").value = i;
        document.getElementById("countdown").innerHTML = (i);

        secsVal = i;
    }
    else {      
        secsVal = "" + secsVal + i;
        console.log(typeof secsVal);//secsVal is a string
        
        secsVal = +secsVal;
        console.log(typeof secsVal); //secsVal is now a number

        document.getElementById("countdown").value = secsVal;
    }
}
<input type="number" id="countdown"/>
<button onclick="valueAssign(5)">Click</button>
Weedoze
  • 13,683
  • 1
  • 33
  • 63
0

How about parsing the String?

"The parseInt() function parses a string and returns an integer." http://www.w3schools.com/jsref/jsref_parseint.asp

rob2universe
  • 7,059
  • 39
  • 54