0

In below snippet code, If i give inputs "9999999999" and "9999999999." in console log both displays the same result "999999999" with out dot.

Am trying to capture dot symbol even after number. Here, only input type number is allowed cannot use text or any other type.

Text box is for number

Number: <input type='number' id=txtNumber'/>

And it's javascript function

$(document).ready(function() {  
   $('#txtNumber').keyup(function () {
     var numbers = $(this).val(); console.log("numbers", numbers);
   });
});

code at JSFiddle

Please help to find solution.

  • 1
    Because the value of `"9999999999."` casted to a number is `9999999999`. Since it's `type='number'` then `.val()` will convert the value into a number. – Spencer Wieczorek Jun 21 '17 at 18:34
  • Possible duplicate of [How to get the raw value an field?](https://stackoverflow.com/questions/18852244/how-to-get-the-raw-value-an-input-type-number-field) – Aravindh Gopi Jun 21 '17 at 18:41
  • Possibly [XY Problem](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem) - *why* do you want to do this, what are you trying to achieve? – freedomn-m Jun 21 '17 at 18:57

2 Answers2

0

The reason is you set type='number'. I suggest you set type='text' and use regular expressions to check if the value in the input is a number(include dot) or not:

  $(document).ready(function() {  
       $('#txtNumber').keyup(function () {
        if ($(this).val().match(/^[0-9]*\.?[0-9]*$/)){ //check if your value is number or not
         var numbers = $(this).val(); console.log("numbers", numbers);
         }
       });
    });
Thai Doan
  • 300
  • 3
  • 14
0

You can use a function to do this:

$(document).ready(function () {
        $('#txtNumber').keyup(function () {
            var numbers = $(this).val(); console.log("numbers", numbers);
            // dump(numbers);
            numbers = parseInt(numbers).toFixed(2);
            console.log(numbers);
        });
    });

It will give you your desired output.

Himanshu Upadhyay
  • 6,558
  • 1
  • 20
  • 33