On several pages I created, it's requested from the user a numerical input. The problem is the Javascript may interpret this input as a string rather than a number. For instance,
var x = document.getElementById("inputx").value;
var y = document.getElementById("inputy").value;
var z = x+y;
document.getElementById("outputParagraph").innerHTML = z;
So, if the user inputted 2 and 3, I would expect the output 5, but it may return 23. It doesn't always happen, but I couldn't notice any pattern.
Usually, I work around this problem doing some innocuous mathematical operations, like multiplying by 1, or doing a varible++ followed by a variable--. It always work. Sometimes I create a whole function to perform this workaround, since it's required in several parts of the code, like on this time calculator page I coded:
//define time class
class time {
constructor(day, hour, minute,
second) {
this.day = day;
this.hour = hour;
this.minute = minute;
this.second = second;
}
}
// this work around forces Javascript to understand inputs as numbers
function workaround(t) {
console.log("working around...");
console.log(typeof t.day);
t.day = t.day * 1;
console.log(typeof t.day);
t.hour = t.hour * 1;
t.minute = t.minute * 1;
t.second = t.second * 1;
}
My question is: is there a more simple, elegant way to solve this issue?