2

I have a project where I want to get numbers only as input so I'm using a input of type number but this also allows decimal seperators etc. how would I prevent the use of , . and e.

I have looked around and couldn't find one that gave the desired result, sinds they either didn't block the decimal inputs, or would allow a user to still paste it in the field.

I have javascript and jquery that I can use, but I do not want to use an external librairy.

If anyone would be able to help me that would be appriciated.

function LimitKeys($id) {        
    $field = document.getElementById($id);
    $value = $($field).val(); //if the value contains multiple e , or . the value is no longer valid and gives me blank
    console.log($value);
    $regex = /[^\d]/;

    $val = $value.replace($regex, "");// cant replace in blank
    console.log($val);
    //$($field).val($val);
}

$('.number-only').keypress(function (event) { //sinds it's on keypress it won't catch the paste of data.
    console.log(this.value);
    var regex = new RegExp("^[0-9]+$");
    var key = String.fromCharCode(!event.charCode ? event.which : event.charCode);
    if (!regex.test(key)) {
        event.preventDefault();
        return false;
    }
});
maam27
  • 444
  • 3
  • 21
  • Try: `$('.number-only').input(function(){this.value=this.value.replace(/\D/g,'')}` – Washington Guedes Nov 08 '16 at 14:13
  • @Liam i only want the digits 0-9 and I assume that it has been asked before since it wouldn't be that rare a question. but i haven't found it by searching, or it would have a answer that didn't quite satisfy my needs. – maam27 Nov 08 '16 at 14:17

1 Answers1

1

Try this code

$(".number-only").on('input', function (e) {
 //if the letter is not digit then display error and don't type anything
 if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
    //display error message
    $(".error").html("Only numbers allowed").show().fadeOut("slow");
           return false;
}
});

Don't forget to create a error class.

Aniket Sahrawat
  • 12,410
  • 3
  • 41
  • 67
  • since this is on keypress it will never filter the contents being pasted in. that is the only issue i have with the second function i posted – maam27 Nov 08 '16 at 14:18
  • @maam27 use onBlur along with this – abhirathore2006 Nov 08 '16 at 14:19
  • 1
    you could use the `on()` function and put multiple event listeners in one rule [check this answer](http://stackoverflow.com/questions/2534089/jquery-multiple-events-to-trigger-the-same-function#answer-2534107) – Kevin Kloet Nov 08 '16 at 14:19