如何使用jQuery只允许HTML输入框中的数字(0-9)?我正在创建一个网页,其中有一个输入文本字段,其中只允许(0,1,2,3,4,5…9)0-9这样的数字字符。我如何使用jQuery来完成这个任务?
4 回答
海绵宝宝撒
TA贡献1809条经验 获得超8个赞
// Numeric only control handlerjQuery.fn.ForceNumericOnly =function(){ return this.each(function() { $(this).keydown(function(e) { var key = e.charCode || e.keyCode || 0; // allow backspace, tab, delete, enter, arrows, numbers and keypad numbers ONLY // home, end, period, and numpad decimal return ( key == 8 || key == 9 || key == 13 || key == 46 || key == 110 || key == 190 || (key >= 35 && key <= 40) || (key >= 48 && key <= 57) || (key >= 96 && key <= 105)); }); });};
$("#yourTextBoxName").ForceNumericOnly();
梦里花落0921
TA贡献1772条经验 获得超6个赞
/^[0-9]+$/.test(input);
// Allow: backspace, delete, tab, escape, enter, ctrl+A and . if ($.inArray(e.keyCode, [46, 8, 9, 27, 13, 110, 190]) !== -1 || // Allow: Ctrl+A (e.keyCode == 65 && e.ctrlKey === true) || // Allow: home, end, left, right (e.keyCode >= 35 && e.keyCode <= 39)) { // let it happen, don't do anything return; } var charValue = String.fromCharCode(e.keyCode) , valid = /^[0-9]+$/.test(charValue); if (!valid) { e.preventDefault(); }
添加回答
举报
0/150
提交
取消