8
4

6 回答 6

14
$(document).ready(function() {
    $('#contactNumber').keyup(function() {
        var numbers = $(this).val();
        $(this).val(numbers.replace(/\D/, ''));
    });
});

这应该用一个空字符 * 替换任何非数字,因为它们被放入,否定一次搜索多个非数字的需要。

于 2012-07-13T05:40:46.380 回答
7

以上都不适用于我,但我找到了一个非常适合我需要的解决方案(禁止输入字段中的特殊字符)。防止和提醒用户。

    <script>
     $("#userlogin").keypress(function(e) {
      if (String.fromCharCode(e.which).match(/[^A-Za-z0-9_ ]/)) {
        e.preventDefault();
        alert("Special characters are not allowed. Use 'A-Z', 'a-z' and '0-9'.");
       }
     });
    </script>
于 2014-04-24T19:42:28.320 回答
1

以前看过这个回答。查看 http://www.texotela.co.uk/code/jquery/numeric/

您可以简单地更改您的班级 ID 并在您的页面上使用此代码:

$(document).ready(function(){
    $(".numeric").numeric();
});

如果您不想使用 jQuery,您可以编写自己的函数并将其称为 onkeyup 事件

请参阅:http ://www.htmlcodetutorial.com/forms/index_famsupp_158.html

另一种选择是使用 step 属性:

http://www.w3.org/TR/html-markup/input.number.html#input.number.attrs.step.float

<input type="number" step="0.01" min="0" >
于 2012-07-13T05:38:00.393 回答
1

type="tel" 是 HTML 5,而不是 jqueryMobile。其浏览器支持 HTML 5 输入类型的较晚设备可以很好地呈现这些框。但是对于旧版本,需要有额外的脚本。脚本已经发布在上面的答案中。

于 2012-09-24T10:50:43.000 回答
0
$('#contactNumber').bind('keypress', function (event) {
        event = event || window.event; canAdd = new Boolean(false);
        canAdd = ((event.charCode > 47) && (event.charCode < 58) || (event.charCode == 32) || (event.charCode == 40) || (event.charCode == 41) || (event.charCode == 43) || (event.charCode == 45) || (event.charCode == 124));
        if (!canAdd && event.charCode)
            return false;
    }); 

但最好使用 HTML5 电话属性

于 2013-05-20T12:00:28.300 回答
0

HTML

 input type="tel" (keypress)="isNumberKey($event)" 

脚本

isNumberKey(evt: any) { < br >
        // to accept only numbers in contact field<br>
        if ( < br >
            (evt.key >= '0' && evt.key <= '9') || < br >
            evt.key == "Backspace" || < br >
            evt.key == "Delete" || < br >
            evt.key == "ArrowLeft" || < br >
            evt.key == "ArrowRight" < br >
        ) { < br > //"Backspace" etc for 'firefox' browser<br>
                return true; < br >
        } < br >
        return false; < br >
}
于 2018-03-16T06:05:25.947 回答