views:

395

answers:

4

I have a javascript code for textbox that will put commas on in digits like (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;
    } 

Now same here I need to restrict user to enter not morethan 5 digits after decimal (ex:

Allow: 12,23,221.34323

Not Allow: 12,23,232.232423

I can change above javascript to work that?

A: 

Not elegant or tested but this should work...

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

}
brad.v
How can handle some times length will allow 2 digits after decimal and some times 5 digits allowed after decimal. If I pass mTextbox.Attributes.Add("OnKeyUp", "javascript:this.value=Comma(this.value,2);")
James123
A: 

You can also try using the JQuery MaskedInput plugin, which works great:

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

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

Use regular expression /(\d+)\.(\d{0,5})$/ as:

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.
}
ring bearer
A: 

today i was working in this senario, I found this agreate way Ihope you find your solution in : http://www.dynamicdrive.com/dynamicindex16/maxlength.htm

or this with style: http://www.dynamicdrive.com/dynamicindex16/limitinput.htm

and here is the code : textbox < textarea maxlength="5" onkeyup="return ismaxlength(this)">

script code :

function ismaxlength(obj) { var mlength=obj.getAttribute? parseInt(obj.getAttribute("maxlength")) : "" if (obj.getAttribute && obj.value.length>mlength) obj.value=obj.value.substring(0,mlength) }

Dani AM