0

Given a number input:

<input type="number" id="create-y-small" name="create-y-small" value="0">

How do I get the value of the input as a number? The following returns a string:

$("#create-y-small").val()

Why is this the default behavior? Surely one should expect a number type input to give a number?

I've looked for answers elsewhere but no luck:

Input value is a string instead of a number - Answers use parsing to parse to a number. I don't want to parse to a number I just want to get the number as a number.

Get variable value from input number - OP seemed happy to get the value as a string

Get the value of a input number in jQuery - Same story

https://www.codegrepper.com/code-examples/javascript/how+to+get+the+value+of+input+number+using+jquery - Same story

TylerH
  • 20,799
  • 66
  • 75
  • 101
Neil
  • 3,020
  • 4
  • 25
  • 48

2 Answers2

2

All input elements in HTML return a string as their value. If you want the result as an int, you have to convert it.

parseInt($("#create-y-small").val())
TylerH
  • 20,799
  • 66
  • 75
  • 101
Daniel Paul
  • 495
  • 1
  • 6
  • 13
2

You can use jQuery's valHooks to change how jQuery returns values.

$.valHooks.number = {
  get: function( elem ) {
    return elem.value * 1;
  }
};

You only need to do this once in your code and then all type=number inputs will instead return a number.

console.log(
  "num is a string",
  $("#num").val() === "1", 
  $("#num").val() === 1, 
  $("#txt").val() === "1",
  $("#txt").val() === 1)

$.valHooks.number = {
  get: function( elem ) {
    return elem.value * 1;
  }
};

// confirm no neffect on type='text'
console.log(
  "num is a number",
  $("#num").val() === "1", 
  $("#num").val() === 1, 
  $("#txt").val() === "1",
  $("#txt").val() === 1)
  
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type='number' id='num' value="1">
<input type='text' id='txt' value="1">
TylerH
  • 20,799
  • 66
  • 75
  • 101
freedomn-m
  • 27,664
  • 8
  • 35
  • 57
  • Nice solution (I upvoted). However there's a caveeat: `"" * 1 = 0`. So one has to treat the missing value case (`""`) separately. Finally I think one can do: `value = parseFloat(elem.value); return isNaN(value) ? "" : value;`. – Stéphane Laurent May 27 '22 at 15:00
  • @StéphaneLaurent if you're using this solution then it's because you want a *number* - returning a `string` (`""`) would be a bad idea. – freedomn-m May 28 '22 at 15:42
  • > I'm using number inputs in the cells of **datatables** table. The empty string is the only way I know to render a blank cell. What kind of problem could it cause? – Stéphane Laurent May 28 '22 at 16:08