Format field as cash

restricts entry to 2dp and formats value as uk cash

by moob

HTML

<input id="cash" type="text" placeholder="£0.00" />
<button id="btn">floatVal</button>

JavaScript

var field = document.getElementById("cash");
var btn = document.getElementById("btn");
var cash = {
    thouSeparator : ",",
    currencySymbol : "£",
    re : new RegExp("[,£]","g"),
    format : function(val) {
        var decPlaces = 2,
            decSeparator = ".",
            thouSeparator = cash.thouSeparator,
            currencySymbol = cash.currencySymbol,
            n = val.replace(cash.re,''),
            i = parseInt(n = Math.abs(+n || 0).toFixed(decPlaces)) + "",
            sign = n < 0 ? "-" : "",
            j = (j = i.length) > 3 ? j % 3 : 0;
        return sign + currencySymbol + (j ? i.substr(0, j) + thouSeparator : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + thouSeparator) + (decPlaces ? decSeparator + Math.abs(n - i).toFixed(decPlaces).slice(2) : "");
    },
    onKeyPress : function(evt) {
        var el = this;
        var charCode = (evt.which) ? evt.which : event.keyCode;
        console.log(charCode);
        var number = el.value.split('.');
        //dissallow anything thats not a number, a dot or a comma
        if (charCode != 44 && charCode != 46 && charCode > 31 && (charCode < 48 || charCode > 57)){
            return false;
        }
        //dissallow typing 2 chars after the dot
        var caratPos = cash.getSelectionStart(el);
        var dotPos = el.value.indexOf(".");
        if( caratPos > dotPos && dotPos>-1 && (number[1].length > 1)){
            return false;
        }
        return true;
    },
    onKeyUp : function(){    
        var el = this;        
        el.value = cash.format(el.value);
    },
    getSelectionStart : function(o) {
        //http://javascript.nwbox.com/cursor_position/
        if (o.createTextRange) {
            var r = document.selection.createRange().duplicate()
            r.moveEnd('character', o.value.length)
            if (r.text == '') return o.value.length
            return o.value.lastIndexOf(r.text)
        } else return o.selectionStart
    },
    toFloat :...