仅在粘贴时将输入限制为数字 [英] Restrict input to number only on pasting
问题描述
我有一个输入类,名为限制数量",我想将输入的字符限制为仅接受数字,我使用了下面的代码,虽然很好,但我想对粘贴进行相同限制的问题在没有完全禁用粘贴的情况下进行输入:
I have an input filed with a class called restrict-numbers which i want to restrict the entered characters to only accept numbers, i used the following code which is great but the problem that i want to make the same restriction works with pasting in the input filed without totally disabling pasting:
function input_only_numbers(){
$("input[type=text]").each(function(){
if( $(this).hasClass("restrict-numbers") ){
$(this).keydown(function(event) {
if ( event.keyCode == 46 || event.keyCode == 8 || event.keyCode == 9 || event.keyCode == 27 ||
// Allow: Ctrl+A
(event.keyCode == 65 && event.ctrlKey === true) ||
// Allow: Ctrl+V
(event.ctrlKey == true && (event.which == '118' || event.which == '86')) ||
// Allow: Ctrl+c
(event.ctrlKey == true && (event.which == '99' || event.which == '67')) ||
// Allow: Ctrl+x
(event.ctrlKey == true && (event.which == '120' || event.which == '88')) ||
// Allow: home, end, left, right
(event.keyCode >= 35 && event.keyCode <= 39)) {
// let it happen, don't do anything
return;
}
else {
// Ensure that it is a number and stop the keypress
if ( event.shiftKey|| (event.keyCode < 48 || event.keyCode > 57) && (event.keyCode < 96 || event.keyCode > 105 ) ){
event.preventDefault();
}
}
});
}
});
}
推荐答案
使用
此外,这也适用于textareas! Moreover this works with textareas also! 或者在用户尝试提交时更好地更改输入, Or better change the input when user tries to submit, 这就是您要执行的操作,您想删除数字以外的字符,所以为什么要花那么多精力,只需在最后将它们删除即可. That's what you are doing, you want to remove the characters, other than numbers, so why make so much efforts, just remove them at the end. 这是我最喜欢的选项, 尝试HTML5 数字输入: Try the HTML5 number input: 对于不兼容的浏览器,有 Modernizr 和 For non-compliant browsers there are Modernizr and Webforms2 fallbacks. 您也可以将粘贴"操作绑定到功能上, You may bind "paste" action to a function too, 这篇关于仅在粘贴时将输入限制为数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!$('form').submit(function () {
if ($('#numeric').value != $('#numeric').value.replace(/[^0-9\.]/g, '')) {
$('#numeric').value = $('#numeric').value.replace(/[^0-9\.]/g, '');
}
});
<input type="number" value="0" min="0">
$( "#input" ).on("paste", function() {
if ($('"#input').val() != $('"#input').val().replace(/[^\d\.]/g,""))
{ $('"#input').val($('"#input').val().replace(/[^\d\.]/g,""));
}
});