十进制后不允许超过5位数。在javascript“OnKeyUp”?

时间:2010-05-05 20:42:06

标签: asp.net javascript

我有一个用于文本框的javascript代码,可以将逗号放在数字中,如(11,23,233)

 mTextbox.Attributes.Add("OnKeyUp", "javascript:this.value=Comma(this.value);")

function Comma(Num) {

        Num += '';
        Num = Num.replace(',', ''); Num = Num.replace(',', ''); Num = Num.replace(',', '');
        Num = Num.replace(',', ''); Num = Num.replace(',', ''); Num = Num.replace(',', '');
        x = Num.split('.');
        x1 = x[0];
        x2 = x.length > 1 ? '.' + x[1] : '';
        var rgx = /(\d+)(\d{3})/;
        while (rgx.test(x1))
            x1 = x1.replace(rgx, '$1' + ',' + '$2');
        return x1 + x2;
    } 

现在我在这里同样需要限制用户输入十进制后不超过5位数(例如:

Allow: 12,23,221.34323

Not Allow: 12,23,232.232423

我可以更改上面的javascript来工作吗?

4 个答案:

答案 0 :(得分:0)

不优雅或经过测试,但这应该有用......

function Comma( Num ) {

    var period = Num.indexOf('.');

    // if you want to just fail...
    if ( Num.length > (period + 6)) throw "too many after decimal point";

    if ( period != -1 ) {
        Num += '00000';
        Num = Num.substr( 0, (period + 6));
    }

    // might want to replace all commas->'' before parsing,
    // this will remove all trailing zeros
    Num = parseFloat( Num.replace( ',', '') );

    ....your stuff

}

答案 1 :(得分:0)

您也可以尝试使用JQuery MaskedInput插件,该插件效果很好:

http://digitalbush.com/projects/masked-input-plugin/

jQuery(function($){
   $("#mTextbox").mask("99,99,999.99999");
});

答案 2 :(得分:0)

将正则表达式/(\d+)\.(\d{0,5})$/用作:

function Comma(Num) {
  Num += '';
  Num = Num.replace(',', ''); Num = Num.replace(',', ''); Num = Num.replace(',', '');
  Num = Num.replace(',', ''); Num = Num.replace(',', ''); Num = Num.replace(',', '');

  var szChkRgx=/(\d+)\.(\d{0,5})$/;

  if(!Num.match(szChkRgx)){
    alert("Only max five decimal places allowed!");
    return;
  }

  //rest of your code.
}

答案 3 :(得分:0)

今天我在这个Senario工作,我找到了这种方式,希望你找到你的解决方案: http://www.dynamicdrive.com/dynamicindex16/maxlength.htm

或带有样式: http://www.dynamicdrive.com/dynamicindex16/limitinput.htm

这是代码: 文本框 < textarea maxlength =“5”onkeyup =“return ismaxlength(this)”>

脚本代码:

函数ismaxlength(obj) { var mlength = obj.getAttribute? parseInt(obj.getAttribute(“maxlength”)):“” if(obj.getAttribute&& obj.value.length> mlength) obj.value = obj.value.substring(0,mlength) }