How to check user inputted decimal separator in the textbox by jquery

↘锁芯ラ 提交于 2019-12-13 07:13:19

问题


I have the plugin format number. And i want to improve it. If user inputted one decimal separator in the textbox , user do not input "," or "." in the textbox.

ex: no allow user input 11111,55,,.44.. --> allow user input:11111,5554455

Here my plugin:

 $.fn.myPlugin = function(options)
{
    options = $.extend({}, {
        thousands: '.',
        decimal: ','
    }, options);

    this.keyup(function()
    {
        $(this).val(function(el, val)
        {
            val = val.replace(/[^\d.,]/g, '').split(options.decimal);
            val[0] = val[0].replace(options.decimal === '.' ? /,/g : /\./g, '');
            val[0] = val[0].replace(/(\d)(?=(\d{3})+$)/g, "$1" + options.thousands);
            return val.join(options.decimal);

        });
    });
};

回答1:


I suppose this is what you're looking for. Whenever you input more than one period or comma it'll just remove it.

$('input').keyup(function(){
    var value = $(this).val(),
        patt = /(,.*?,|\..*?\.)/;
    if (patt.test(value)) { $(this).val(value.slice(0, -1)); }
});

http://jsfiddle.net/elclanrs/t8G2q/4/




回答2:


Not sure I get what your looking for, but here's a poorly written example done in a hurry to just show how you can do something like this with iteration:

$("#test").on('keyup', function() {
    var V = $(this).val().split(''), A=[], L=V.length;
    for (var i=0; i<L; i++) {
        var E=V[i];
        if (E=='.' && A.indexOf(E)!=-1) {}else{A.push(E);}
        var Q=A.join('');
    }
    $(this).val(Q);
});

There's a fiddle here for trying it?




回答3:


@minh, if you simply want to check that there is only one "," or "." in the inputted number, you can simply do something like:

val.match(/^\d+([.,]\d+)?$/)

I may have misunderstood exactly what you want to check for. If so, please post a comment.



来源:https://stackoverflow.com/questions/9255142/how-to-check-user-inputted-decimal-separator-in-the-textbox-by-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!