jQuery: what is the best way to restrict “number”-

2019-01-01 04:53发布

What is the best way to restrict "number"-only input for textboxes?

I am looking for something that allows decimal points.

I see a lot of examples. But have yet to decide which one to use.

Update from Praveen Jeganathan

No more plugins, jQuery has implemented its own jQuery.isNumeric() added in v1.7. See: https://stackoverflow.com/a/20186188/66767

30条回答
旧时光的记忆
2楼-- · 2019-01-01 05:10

You dont see alphabets magical appearance and disappearance on key down. This works on mouse paste too.

$('#txtInt').bind('input propertychange', function () {
    $(this).val($(this).val().replace(/[^0-9]/g, ''));
});
查看更多
倾城一夜雪
3楼-- · 2019-01-01 05:11

I think this is a good way of solving this problem and it's extremely simple:

$(function() {
    var pastValue, pastSelectionStart, pastSelectionEnd;

    $("input").on("keydown", function() {
        pastValue          = this.value;
        pastSelectionStart = this.selectionStart;
        pastSelectionEnd   = this.selectionEnd;
    }).on("input propertychange", function() {
        var regex = /^[0-9]+\.?[0-9]*$/;

        if (this.value.length > 0 && !regex.test(this.value)) {
            this.value          = pastValue;
            this.selectionStart = pastSelectionStart;
            this.selectionEnd   = pastSelectionEnd;
        }
    });
});

Example: JSFiddle

Scenarios covered

Most similar recommendations here fail at least one of these or require a lot of code to cover all these scenarios.

  1. Only allows 1 decimal point.
  2. Allows home, end, and the arrow keys.
  3. Allows delete and backspace to be used at any index.
  4. Allows editing at any index (as long as the input matches the regex).
  5. Allows ctrl+v and shift+insert for valid input (same with right click + paste).
  6. Doesn't flicker the text value because the keyup event is not used.
  7. Restores the selection after invalid input.

Scenarios failed

  • Starting with 0.5 and deleting only the zero will not work. This can be fixed by changing the regex to /^[0-9]*\.?[0-9]*$/ and then adding a blur event to prepend a 0 when the textbox starts with a decimal point (if desired). See this advanced scenario for a better idea of how to fix this.

Plugin

I created this simple jquery plugin to make this easier:

$("input").limitRegex(/^[0-9]+\.?[0-9]*$/);
查看更多
琉璃瓶的回忆
4楼-- · 2019-01-01 05:12

Update

There is a new and very simple solution for this:

It allows you to use any kind of input filter on a text <input>, including various numeric filters. This will correctly handle Copy+Paste, Drag+Drop, keyboard shortcuts, context menu operations, non-typeable keys, and all keyboard layouts.

See this answer or try it yourself on JSFiddle.

jquery.numeric plugin

I've successfully implemented many forms with the jquery.numeric plugin.

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

Moreover this works with textareas also!

However, note that Ctrl+A, Copy+Paste (via context menu) and Drag+Drop will not work as expected.

HTML 5

With wider support for the HTML 5 standard, we can use pattern attribute and number type for input elements to restrict number only input. In some browsers (notably Google Chrome), it works to restrict pasting non-numeric content as well. More information about number and other newer input types is available here.

查看更多
无与为乐者.
5楼-- · 2019-01-01 05:13

Other way to keep the caret position on the input:

$(document).ready(function() {
  $('.numbersOnly').on('input', function() {
    var position = this.selectionStart - 1;

    fixed = this.value.replace(/[^0-9\.]/g, '');  //remove all but number and .
    if(fixed.charAt(0) === '.')                  //can't start with .
      fixed = fixed.slice(1);

    var pos = fixed.indexOf(".") + 1;
    if(pos >= 0)
      fixed = fixed.substr(0,pos) + fixed.slice(pos).replace('.', '');  //avoid more than one .

    if (this.value !== fixed) {
      this.value = fixed;
      this.selectionStart = position;
      this.selectionEnd = position;
    }
  });
});

Advantages:

  1. The user can use the arrow keys, Backspace, Delete, ...
  2. Works when you want to paste numbers

Plunker: Demo working

查看更多
萌妹纸的霸气范
6楼-- · 2019-01-01 05:13

I used this,with good results..

ini=$("#id").val();
a=0;
$("#id").keyup(function(e){
    var charcode = (e.which) ? e.which : e.keyCode;
    // for decimal point
    if(!(charcode===190 || charcode===110))
    {           // for numeric keys andcontrol keys
        if (!((charcode>=33 && charcode<=57) || 
        // for numpad numeric keys
        (charcode>=96 && charcode<=105) 
        // for backspace
        || charcode==8)) 
        {
            alert("Sorry! Only numeric values allowed.");
            $("#id").val(ini);
        }
        // to include decimal point if first one has been deleted.
        if(charcode===8)
        {
            ini=ini.split("").reverse();
            if(ini[0]==".")
            a=0;                 
        }
    }
    else
    {
        if(a==1)
        {
            alert("Sorry! Second decimal point not allowed.");
            $("#id").val(ini);
        }
        a=1;
    }
    ini=$("#id").val();
});


find keycodes at http://www.cambiaresearch.com/articles/15/javascript-char-codes-key-codes
查看更多
无色无味的生活
7楼-- · 2019-01-01 05:14

I just found an even better plug-in. Gives you much more control. Say you have a DOB field where you need it be numeric but also accepts "/" or "-" characters.

It works great!

Check it out at http://itgroup.com.ph/alphanumeric/.

查看更多
登录 后发表回答