JQuery允许小数点后只有两个数字

时间:2022-06-02 17:07:42

I found the following JQuery function here which prevents a user from entering anything that's not a number or a single decimal. The function works well but I'd like to improve it to prevent the user from entering 3 or more decimal places i.e. disallow 99.999 and allow 99.99. Any ideas?

我在这里找到了以下JQuery函数,它阻止用户输入任何不是数字或小数的内容。这个功能很好,但是我想改进它,防止用户输入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();           
            }   
     };

7 个解决方案

#1


39  

The logic is every time a user entering a number you have to check two things.

逻辑是每次用户输入一个数字时,你必须检查两件事。

  1. Has the user entered decimal point?
  2. 用户是否输入了小数点?
  3. Are the decimal places more than two?
  4. 小数位数大于2吗?

For the first one you can use $(this).val().indexOf('.') != -1

For the second one you can use $(this).val().substring($(this).val().indexOf('.'), $(this).val().indexOf('.').length).length > 2

对于第一个,可以使用$(this).val(). indexof('.') != -1;对于第二个,可以使用$(this).val().substring($(this).val().index of ('.)), $(this).val('.).index of ('.).length)。长度> 2

EDIT-1
Also, you have to add event.which != 0 && event.which != 8 so that arrow keys and backspace work in Firefox (Manoj comment)

EDIT-1也必须添加事件。哪个!= 0 &&事件。哪个!= 8以便在Firefox中使用箭头键和退格(Manoj评论)

EDIT-2
Also, you have to add $(this)[0].selectionStart >= text.length - 2 so that you can add digits if the cursor is to the left of the decimal point (BIdesi comment)

EDIT-2还必须添加$(this)[0]。selectionStart > =文本。长度- 2,如果光标在小数点的左边,您可以添加数字(BIdesi注释)

EDIT-3
Also, you have to check if user deleted . and placed it somewhere else creating a value with more than 2 digits after the decimal. So you have to add $this.val($this.val().substring(0, $this.val().indexOf('.') + 3)); for cutting extra digits (Gilberto Sánchez comment)

编辑-3,您还必须检查用户是否删除。然后把它放在其他地方,用小数点后2位的数字创建一个值。所以你需要加上$this。val($this。val()substring(0,this.val美元().indexOf(' . ')+ 3));为了减少额外的数字(Gilberto Sanchez评论)

EDIT-4
To handle pasted data, you must bind a paste event handler.Then you have to check if pasted data have . withtext.indexOf('.') > -1 and more than 2 digits after the decimal with text.substring(text.indexOf('.')).length > 3. If so, you have to cut extra digits. Also you have to check that user entered numeric input with $.isNumeric() (darasd comment).

要处理已粘贴的数据,必须绑定一个粘贴事件处理程序。然后你必须检查粘贴的数据是否有。使用text.indexOf('.' .') > -1和文本。substring(text.indexOf('.' .'))的小数点后超过两位数。长度> 3。如果是这样的话,你就得减少额外的数字。此外,您还必须检查用户输入的数值输入是否带有$. isnumeric () (darasd注释)。

Here is the code:

这是代码:

$('.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" />

#2


3  

I've updated the function for a few extra cases.

我已经为一些额外的情况更新了函数。

  1. It will allow negative numbers
  2. 可以是负数
  3. It will allow you to edit the left of the decimal when there are already 2 digits to the right
  4. 当小数点右边已经有两位数字时,它将允许您编辑小数点的左边
  5. It allows you to use the arrow keys and backspace when you are in Firefox
  6. 它允许您在Firefox中使用箭头键和退格
  7. It also handles pasted data
  8. 它还处理粘贴的数据

/**
 * 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" />

#3


2  

It can also be done with a regular expression:

它也可以用正则表达式来完成:

    $('.class').on('input', function () {
        this.value = this.value.match(/^\d+\.?\d{0,2}/);
    });

Name the css selector .class to whatever you like and put it on the input.

将css selector .class命名为任何你喜欢的,并将它放在输入中。

#4


1  

thank you! I have added the possibility of deleting the numbers and '.' once typed:

谢谢你!我增加了删除数字和'的可能性。一旦输入:

The event.keyCode !== 8 does that action for backspace.

该事件。keyCode !== 8对backspace的操作。

The event.keyCode !== 46 does that action for delete.

该事件。keyCode !== 46,删除操作。

$( 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();
        }
    }
  });
});

#5


0  

I have updated this routine to allow standard editing features as these were prevented in the above code. (This routine is just for processing a float but can be adapted to allow only 2 digits after the decimal)

我已经更新了这个例程,以允许标准的编辑功能,因为这些功能在上面的代码中被阻止了。(此例程仅用于处理浮点数,但可调整为只允许小数点后两位数字)

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();
}

#6


0  

Try this

试试这个

HTML

HTML

<input type="text" id="min_rent" name="min_rent" onkeypress="return isPrice(event,$('#min_rent').val())">

Jquery

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;
}

Worked Link demo

链接演示工作

#7


0  

Numeric values With Decimal Point up to 2 decimal point validation. Dependency jQuery.

数字值小数点后2位的验证。jQuery的依赖。

HTML -

HTML—

<span>Float</span>
<input type="text" name="numeric" class='allownumericwithdecimal'>
<div>Numeric values only allowed  (With Decimal Point) </div>

JQuery Code -

JQuery代码。

Method 1-

方法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();
     }
 });

Method 2 -

方法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();
     }
 });

#1


39  

The logic is every time a user entering a number you have to check two things.

逻辑是每次用户输入一个数字时,你必须检查两件事。

  1. Has the user entered decimal point?
  2. 用户是否输入了小数点?
  3. Are the decimal places more than two?
  4. 小数位数大于2吗?

For the first one you can use $(this).val().indexOf('.') != -1

For the second one you can use $(this).val().substring($(this).val().indexOf('.'), $(this).val().indexOf('.').length).length > 2

对于第一个,可以使用$(this).val(). indexof('.') != -1;对于第二个,可以使用$(this).val().substring($(this).val().index of ('.)), $(this).val('.).index of ('.).length)。长度> 2

EDIT-1
Also, you have to add event.which != 0 && event.which != 8 so that arrow keys and backspace work in Firefox (Manoj comment)

EDIT-1也必须添加事件。哪个!= 0 &&事件。哪个!= 8以便在Firefox中使用箭头键和退格(Manoj评论)

EDIT-2
Also, you have to add $(this)[0].selectionStart >= text.length - 2 so that you can add digits if the cursor is to the left of the decimal point (BIdesi comment)

EDIT-2还必须添加$(this)[0]。selectionStart > =文本。长度- 2,如果光标在小数点的左边,您可以添加数字(BIdesi注释)

EDIT-3
Also, you have to check if user deleted . and placed it somewhere else creating a value with more than 2 digits after the decimal. So you have to add $this.val($this.val().substring(0, $this.val().indexOf('.') + 3)); for cutting extra digits (Gilberto Sánchez comment)

编辑-3,您还必须检查用户是否删除。然后把它放在其他地方,用小数点后2位的数字创建一个值。所以你需要加上$this。val($this。val()substring(0,this.val美元().indexOf(' . ')+ 3));为了减少额外的数字(Gilberto Sanchez评论)

EDIT-4
To handle pasted data, you must bind a paste event handler.Then you have to check if pasted data have . withtext.indexOf('.') > -1 and more than 2 digits after the decimal with text.substring(text.indexOf('.')).length > 3. If so, you have to cut extra digits. Also you have to check that user entered numeric input with $.isNumeric() (darasd comment).

要处理已粘贴的数据,必须绑定一个粘贴事件处理程序。然后你必须检查粘贴的数据是否有。使用text.indexOf('.' .') > -1和文本。substring(text.indexOf('.' .'))的小数点后超过两位数。长度> 3。如果是这样的话,你就得减少额外的数字。此外,您还必须检查用户输入的数值输入是否带有$. isnumeric () (darasd注释)。

Here is the code:

这是代码:

$('.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" />

#2


3  

I've updated the function for a few extra cases.

我已经为一些额外的情况更新了函数。

  1. It will allow negative numbers
  2. 可以是负数
  3. It will allow you to edit the left of the decimal when there are already 2 digits to the right
  4. 当小数点右边已经有两位数字时,它将允许您编辑小数点的左边
  5. It allows you to use the arrow keys and backspace when you are in Firefox
  6. 它允许您在Firefox中使用箭头键和退格
  7. It also handles pasted data
  8. 它还处理粘贴的数据

/**
 * 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" />

#3


2  

It can also be done with a regular expression:

它也可以用正则表达式来完成:

    $('.class').on('input', function () {
        this.value = this.value.match(/^\d+\.?\d{0,2}/);
    });

Name the css selector .class to whatever you like and put it on the input.

将css selector .class命名为任何你喜欢的,并将它放在输入中。

#4


1  

thank you! I have added the possibility of deleting the numbers and '.' once typed:

谢谢你!我增加了删除数字和'的可能性。一旦输入:

The event.keyCode !== 8 does that action for backspace.

该事件。keyCode !== 8对backspace的操作。

The event.keyCode !== 46 does that action for delete.

该事件。keyCode !== 46,删除操作。

$( 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();
        }
    }
  });
});

#5


0  

I have updated this routine to allow standard editing features as these were prevented in the above code. (This routine is just for processing a float but can be adapted to allow only 2 digits after the decimal)

我已经更新了这个例程,以允许标准的编辑功能,因为这些功能在上面的代码中被阻止了。(此例程仅用于处理浮点数,但可调整为只允许小数点后两位数字)

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();
}

#6


0  

Try this

试试这个

HTML

HTML

<input type="text" id="min_rent" name="min_rent" onkeypress="return isPrice(event,$('#min_rent').val())">

Jquery

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;
}

Worked Link demo

链接演示工作

#7


0  

Numeric values With Decimal Point up to 2 decimal point validation. Dependency jQuery.

数字值小数点后2位的验证。jQuery的依赖。

HTML -

HTML—

<span>Float</span>
<input type="text" name="numeric" class='allownumericwithdecimal'>
<div>Numeric values only allowed  (With Decimal Point) </div>

JQuery Code -

JQuery代码。

Method 1-

方法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();
     }
 });

Method 2 -

方法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();
     }
 });