input and javascript tag

Asked

Viewed 247 times

3

Hello,

My question is this:

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, number type input, and a JS function that takes data from that input.

my doubt is the following, there was the need to make the conversion to Integer in JS, because the numbers were being understood as string, and instead of adding 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 treats it later?

1 answer

3


This is 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()">

  • 1

    Thank you,valueAsNumber would be hidden properties? hidden attributes or something? in the material I consult https://www.w3schools.com/tags/tag_input.asp there is no such attribute or property

  • 1

    No @Nicolasguilherme, w3schools actually has nothing to do with W3, probably why it’s not there.

Browser other questions tagged

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