0

I have a fiddle here that removes the last character from the input when the user types . However it seems .length ignores the decimal when there are no numbers after it.

For example: currently when the user types 20., it will be cut to 2 instead of 20.

How can I detect this and remove the decimal once the user types it?

John
  • 159
  • 2
  • 13
  • Try this https://jsfiddle.net/hL8ca6zp/ –  May 16 '17 at 01:35
  • You should post this as answer. Can be useful to others. – Sasang May 16 '17 at 01:36
  • @engineeriscool thanks for the comment! Unfortunately I'm looking for a solution where the input also has the attribute `type="number"`. – John May 16 '17 at 01:37
  • @engineeriscool You can still enter some numbers and then put cursor in front and put '.' – vabii May 16 '17 at 01:38
  • @vabii just change `slice` to `.replace(/\./g,'')` –  May 16 '17 at 01:40
  • 2
    The issue is what `type="number"` validates as a number, even when doing `$(this).val($(this).val().replace(".",""))` the problem is that `.val()` won't include the `.` because `20.` is an invalid number so `.value` will be `20`. – Spencer Wieczorek May 16 '17 at 01:42
  • Possible duplicate of [HTML5: number input type that takes only integers?](http://stackoverflow.com/questions/8808590/html5-number-input-type-that-takes-only-integers) – John Wu May 16 '17 at 02:33

1 Answers1

1

I think your requirement is to ignore it when a user types the period.

So all you need is this (notice the event is on keydown and not keyup):

$('input').on('keydown', function(e) {
    if (e.keyCode == 190 || e.keyCode == 110){
        e.preventDefault();
    }
});

Or, even easier, attribute the input so it only takes whole numbers:

<input type="number" min="0" step="1"/>
John Wu
  • 50,556
  • 8
  • 44
  • 80