input tag and javascript

2

Hello,

My question is the following

HTML

<input id="cakeDonuts" type="number" name="numCake" min="0" value="" onchange="updateOrder()">


<input id="glazedDonuts" type="number" name="numGlazed" min="0" value="" onchange="updateOrder()">

JS

function updateOrder(){

var numCake = parseInt(document.getElementById("cakeDonuts").value);
var numGlazed = parseInt(document.getElementById("glazedDonuts").value);

}

Knowing that I have an html tag, input of type number, and a JS function that receives data from this input.

My question is as follows, there was a need to do the conversion to Integer in JS because the numbers were being understood as string, and instead of adding it was concatenating.

Knowing all this, the real question is, who sends these numbers as text? the html input tag of type number itself sends the numbers as text (String)?

Or JS by default converts everything it receives to text (String), and the programmer who handles this later?

    
asked by anonymous 12.06.2017 / 22:42

1 answer

2

This happens because HTMLInputElement . value will return a string. You could use HTMLInputElement valueAsNumber :

Example

function updateOrder() {

  var numCake = document.getElementById("cakeDonuts").valueAsNumber;
  console.log(typeof numCake)

}
<input id="cakeDonuts" type="number" name="numCake" min="0" value="" onchange="updateOrder()">
    
12.06.2017 / 22:55