Javascript - validation, numbers only

前端 未结 14 1714
感动是毒
感动是毒 2020-12-08 09:52

I\'m trying to get my login form to only validate if only numbers were inputted. I can it to work if the input is only digits, but when i type any characters after a number,

14条回答
  •  生来不讨喜
    2020-12-08 10:23

    Using the form you already have:

    var input = document.querySelector('form[name=myForm] #username');
    
    input.onkeyup = function() {
        var patterns = /[^0-9]/g;
        var caretPos = this.selectionStart;
    
        this.value = input.value.replace(patterns, '');
        this.setSelectionRange(caretPos, caretPos);
    }
    

    This will delete all non-digits after the key is released.

提交回复
热议问题