Best way to restrict a text field to numbers only?

前端 未结 29 1683
长情又很酷
长情又很酷 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

    This is a variation on Robert's answer that allows a single decimal point to be entered. If a decimal point has already been entered, only numbers are accepted as input.

    JSFiddle - decimal number input

    // Allow only decimal number input
    
    $('#decimalInput').keypress(function (e) {
        var a = [];
        var k = e.which;
    
        for (i = 48; i < 58; i++)
        a.push(i);
    
        // allow a max of 1 decimal point to be entered
        if (this.value.indexOf(".") === -1) {
            a.push(46);
        }
    
        if (!(a.indexOf(k) >= 0)) e.preventDefault();
    
        $('span').text('KeyCode: ' + k);
    });
    

提交回复
热议问题