我发现了以下JQuery函数here,它阻止用户输入任何不是数字或单个小数的内容。该功能运行良好,但我想改进它以防止用户输入3个或更多小数位,即禁止99.999并允许99.99。有什么想法吗?
function checkForInvalidCharacters(event, inputBox){
if ((event.which != 46 || inputBox.val().indexOf('.') != -1) && (event.which < 48 || event.which > 57)) {
event.preventDefault();
}
};
答案 0 :(得分:45)
逻辑是每次用户输入一个号码时你必须检查两件事。
对于第一个,您可以使用$(this).val().indexOf('.') != -1
对于第二个,您可以使用$(this).val().substring($(this).val().indexOf('.'), $(this).val().indexOf('.').length).length > 2
修改-1 强>
此外,您必须添加event.which != 0 && event.which != 8
,以便箭头键和退格键在Firefox中工作(Manoj评论)
修改-2 强>
此外,您必须添加$(this)[0].selectionStart >= text.length - 2
,以便在光标位于小数点左侧时可以添加数字(BIdesi注释)
修改-3 强>
此外,您必须检查用户是否已删除.
并将其放置在其他位置以创建小数点后超过2位的值。所以你必须添加
$this.val($this.val().substring(0, $this.val().indexOf('.') + 3));
用于削减额外数字(GilbertoSánchez评论)
修改-4 强>
要处理粘贴的数据,您必须绑定粘贴事件处理程序。然后,您必须检查粘贴的数据是否.
与text.indexOf('.') > -1
一致,小数点后的text.substring(text.indexOf('.')).length > 3
是否超过2位数。如果是这样,你必须削减额外的数字。此外,您必须检查该用户是否输入了$.isNumeric()
(darasd comment)的数字输入。
以下是代码:
$('.number').keypress(function(event) {
var $this = $(this);
if ((event.which != 46 || $this.val().indexOf('.') != -1) &&
((event.which < 48 || event.which > 57) &&
(event.which != 0 && event.which != 8))) {
event.preventDefault();
}
var text = $(this).val();
if ((event.which == 46) && (text.indexOf('.') == -1)) {
setTimeout(function() {
if ($this.val().substring($this.val().indexOf('.')).length > 3) {
$this.val($this.val().substring(0, $this.val().indexOf('.') + 3));
}
}, 1);
}
if ((text.indexOf('.') != -1) &&
(text.substring(text.indexOf('.')).length > 2) &&
(event.which != 0 && event.which != 8) &&
($(this)[0].selectionStart >= text.length - 2)) {
event.preventDefault();
}
});
$('.number').bind("paste", function(e) {
var text = e.originalEvent.clipboardData.getData('Text');
if ($.isNumeric(text)) {
if ((text.substring(text.indexOf('.')).length > 3) && (text.indexOf('.') > -1)) {
e.preventDefault();
$(this).val(text.substring(0, text.indexOf('.') + 3));
}
}
else {
e.preventDefault();
}
});
.number {
padding: 5px 10px;
font-size: 16px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="number" />
答案 1 :(得分:3)
我已经更新了一些额外案例的功能。
/**
* Given an input field, this function will only allow numbers with up to two decimal places to be input.
* @param {object} element
* @return {number}
*/
function forceNumber(element) {
element
.data("oldValue", '')
.bind("paste", function(e) {
var validNumber = /^[-]?\d+(\.\d{1,2})?$/;
element.data('oldValue', element.val())
setTimeout(function() {
if (!validNumber.test(element.val()))
element.val(element.data('oldValue'));
}, 0);
});
element
.keypress(function(event) {
var text = $(this).val();
if ((event.which != 46 || text.indexOf('.') != -1) && //if the keypress is not a . or there is already a decimal point
((event.which < 48 || event.which > 57) && //and you try to enter something that isn't a number
(event.which != 45 || (element[0].selectionStart != 0 || text.indexOf('-') != -1)) && //and the keypress is not a -, or the cursor is not at the beginning, or there is already a -
(event.which != 0 && event.which != 8))) { //and the keypress is not a backspace or arrow key (in FF)
event.preventDefault(); //cancel the keypress
}
if ((text.indexOf('.') != -1) && (text.substring(text.indexOf('.')).length > 2) && //if there is a decimal point, and there are more than two digits after the decimal point
((element[0].selectionStart - element[0].selectionEnd) == 0) && //and no part of the input is selected
(element[0].selectionStart >= element.val().length - 2) && //and the cursor is to the right of the decimal point
(event.which != 45 || (element[0].selectionStart != 0 || text.indexOf('-') != -1)) && //and the keypress is not a -, or the cursor is not at the beginning, or there is already a -
(event.which != 0 && event.which != 8)) { //and the keypress is not a backspace or arrow key (in FF)
event.preventDefault(); //cancel the keypress
}
});
}
forceNumber($("#myInput"));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="myInput" />
答案 2 :(得分:3)
也可以使用正则表达式:
$('.class').on('input', function () {
this.value = this.value.match(/^\d+\.?\d{0,2}/);
});
将css选择器 .class 命名为您喜欢的任何内容并将其放在输入上。
答案 3 :(得分:2)
event.keyCode !== 8
为退格执行该操作。
event.keyCode !== 46
执行 delete 的操作。
$( document ).ready(function() {
$('#Ds_Merchant_Amount').keypress(function(event) {
if ((event.which != 46 || $(this).val().indexOf('.') != -1) && (event.which < 48 || event.which > 57) ) {
if (event.keyCode !== 8 && event.keyCode !== 46 ){ //exception
event.preventDefault();
}
}
if(($(this).val().indexOf('.') != -1) && ($(this).val().substring($(this).val().indexOf('.'),$(this).val().indexOf('.').length).length>2 )){
if (event.keyCode !== 8 && event.keyCode !== 46 ){ //exception
event.preventDefault();
}
}
});
});
答案 4 :(得分:0)
我已更新此例程以允许标准编辑功能,因为在上面的代码中阻止了这些功能。 (此例程仅用于处理浮点数,但可以调整为仅允许小数点后的2位数)
var value = $(this).val().toString();
// Allowed Keys
if (event.which === 8 || event.which === 46 // Character delete
|| event.which === 16 || event.which === 17 // Modifier Key
|| event.which === 37 || event.which === 39 // Arrow Keys
|| (event.key.toLowerCase() === "a" && event.ctrlKey) // Select All
|| (event.key.toLowerCase() === "c" && event.ctrlKey) // Copy
|| (event.key.toLowerCase() === "x" && event.ctrlKey) // Cut
|| (event.key.toLowerCase() === "v" && event.ctrlKey) // Paste
|| (event.which === 45 && event.ctrlKey) // Old school copy (CTRL + INSERT)
|| (event.which === 46 && event.shiftKey) // Old school cut (SHIFT + DELETE)
|| (event.which === 45 && event.shiftKey) // Old school paste (SHIFT + INSERT)
|| (event.which === 35) // END
|| (event.which === 36) // HOME
|| (event.which === 35 && event.shiftKey) // SHIFT + END
|| (event.which === 36 && event.shiftKey) // SHIFT + HOME
)
{
return;
}
else if (event.which === 190) // Process decimal point
{
if (value == "" || value.indexOf(".") > -1)
{
event.preventDefault();
}
}
else if (event.which < 48 || event.which > 57 || event.ctrlKey || event.shiftKey) // Reject anything else that isn't a number
{
event.preventDefault();
}
答案 5 :(得分:0)
试试这个
<强> HTML 强>
<input type="text" id="min_rent" name="min_rent" onkeypress="return isPrice(event,$('#min_rent').val())">
<强> Jquery的强>
function isPrice(evt,value) {
var charCode = (evt.which) ? evt.which : event.keyCode;
if((value.indexOf('.')!=-1) && (charCode != 45 && (charCode < 48 || charCode > 57)))
return false;
else if(charCode != 45 && (charCode != 46 || $(this).val().indexOf('.') != -1) && (charCode < 48 || charCode > 57))
return false;
return true;
}
工作链接 demo 强>
答案 6 :(得分:0)
数字值使用小数点最多2位小数点验证。 依赖 jQuery 。
HTML -
<span>Float</span>
<input type="text" name="numeric" class='allownumericwithdecimal'>
<div>Numeric values only allowed (With Decimal Point) </div>
JQuery代码 -
方法1 -
$(".allownumericwithdecimal").on("keypress keyup blur", function (event) {
var patt = new RegExp(/[0-9]*[.]{1}[0-9]{2}/i);
var matchedString = $(this).val().match(patt);
if (matchedString) {
$(this).val(matchedString);
}
if ((event.which != 46 || $(this).val().indexOf('.') != -1) && (event.which < 48 || event.which > 57)) {
event.preventDefault();
}
});
方法2 -
$(".allownumericwithdecimal").on("keypress keyup blur", function (event) {
var patt = new RegExp(/(?<=\.\d\d).+/i);
$(this).val($(this).val().replace(patt, ''));
if ((event.which != 46 || $(this).val().indexOf('.') != -1) && (event.which < 48 || event.which > 57)) {
event.preventDefault();
}
});