Best way to restrict a text field to numbers only?

前端 未结 29 1656
长情又很酷
长情又很酷 2020-12-04 22:01

I\'m using the following Javascript to restrict a text field on my website to only accept numerical input, and no other letters or characters. The problem is, it REALLY reje

29条回答
  •  情歌与酒
    2020-12-04 22:27

    Just use regex to get rid of any non number characters whenever a key is pressed or the textbox loses focus.

    var numInput;
    window.onload = function () {   
        numInput = document.getElementById('numonly');
        numInput.onkeydown = numInput.onblur = numInput.onkeyup = function()
        {
            numInput.value = numInput.value.replace(/[^0-9]+/,"");
        }
    }
    

提交回复
热议问题