javascript - Auto populate Comma and Decimal in Text Box -


i have text box of dollar amount ( html below ). trying add css or jquery auto populate comma , decimal when user enters value in text box. eg , if user enters 123456789 , should automatically become 12,345,667.89 .

<html:text styleid="incomeperperiod" styleclass="textbox" property="employment.incomeperperiod" maxlength="10" /> 

i added below class html code above it's not working. can please me on how achieve ?

class="form-control text-right number" 

it might or might not simpler pure js string functions here regexp version.

the thing is, couldn't find way group entered number string ??n nnn ... nnn nnn nn matches regexp. relatively simple groups nn nnn nnn ... nnn n??. regex;

/(^\d{2})|(\d{1,3})(?=\d{1,3}|$)/g 

so reverse string start follows;

array.prototype.reduce.call(str,(p,c) => c + p) 

then applying regex reversed string .match(rex) work like, "123456789" yield [ '98', '765', '432', '1' ].

then of course join them . , , @ proper positions

.reduce((p,c,i) => - 1 ? p + "," + c : p + "." + c) 

and 98.765,432,1. need reverse string again of course. here working example.

function formatnumber(e){    var rex = /(^\d{2})|(\d{1,3})(?=\d{1,3}|$)/g,        val = this.value.replace(/^0+|\.|,/g,""),        res;            if (val.length) {      res = array.prototype.reduce.call(val, (p,c) => c + p)            // reverse pure numbers string                 .match(rex)                                            // groups in array                 .reduce((p,c,i) => - 1 ? p + "," + c : p + "." + c); // insert (.) , (,) accordingly      res += /\.|,/.test(res) ? "" : ".0";                              // test if res has (.) or (,) in      this.value = array.prototype.reduce.call(res, (p,c) => c + p);    // reverse string , display    }  }    var ni = document.getelementbyid("numin");    ni.addeventlistener("keyup", formatnumber);
<input id="numin" placeholder="enter number">

the res += /\.|,/.test(res) ? "" : ".0"; part takes care of prefixing "0." when have cents.


Comments

Popular posts from this blog

ios - MKAnnotationView layer is not of expected type: MKLayer -

ZeroMQ on Windows, with Qt Creator -

unity3d - Unity SceneManager.LoadScene quits application -