Best way to restrict a text field to numbers only?

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

    My functions:

    $('.input_integer_only').on('input', function(e) {
        $(this).val($(this).val().replace(/[^0-9]/g, ''));
    });
    
    
    $('.input_float_only').on('input', function(e) {
        var $var = $(this).val().replace(/[^0-9\.]/g, '');
        var $aVar = $var.split('.');
    
        if($aVar.length > 2) {
            $var = $aVar[0] + '.' + $aVar[1];
        }
    
        $(this).val($var);
    });
    

提交回复
热议问题