keydown prints me empty string

1

I have a problem wanting to validate the value of an input, since I need to be pure numbers that the user enters, but I press the first key and it gives me an empty string, and I really do not know what I'm doing wrong, if Somebody help me I'll thank them, I've been trying for a while and it's not coming out.

var amountNumber = $('#amount-number');
    amountNumber.keydown(function(e) {
    var inputNumber = amountNumber.val();
    console.log(inputNumber);
    var exRegNumber = /([0-9])/g;
    if(!(exRegNumber.test(inputNumber))){
        e.preventDefault();
    };
});
    
asked by Nancy Zj 15.12.2017 в 02:09
source

2 answers

2

Fast answer, you can use input of the numeric type. Its default value is 0.

var amountNumber = $('#amount-number');
    amountNumber.keydown(function(e) {
    var inputNumber = amountNumber.val();
    console.log(inputNumber);
    var exRegNumber = /([0-9])/g;
    if(!(exRegNumber.test(inputNumber))){
        e.preventDefault();
    };
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="number" id="amount-number" value="0" min="0"/>
    
answered by 15.12.2017 в 02:11
1

Good for these cases you can use the library Mask that helps us add masks to the input and solve in cases of needing only numbers or letters among others I hope you help greetings.

It is very easy to use and as you can see, you can pass it as a parameter REGULAR EXPRESSIONS and it gives you the freedom to restrict the user.

Functional example

$('#amount-number').mask('ZZ',{translation:  {'Z': {pattern: /[0-9\s]/, recursive: true}}});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.mask/1.14.13/jquery.mask.min.js"></script>

<input placeholder="Ingresa solo numeros" id="amount-number" type="text">
    
answered by 15.12.2017 в 02:19