Last active
August 29, 2015 14:02
-
-
Save kenu/a3e836773f86ae3c4b40 to your computer and use it in GitHub Desktop.
jquery plugin for money
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$.fn.money = function() { | |
var M = {}; | |
M = { | |
prefix: "$ ", | |
floatFlag: "off", | |
format: function() { | |
M.config(this); | |
var n = $(this).val().replace(/[\$\s,]/g, ""); | |
var strn = "" + parseInt(n); | |
if (strn == "NaN") { | |
return; | |
} | |
var arrn = strn.split(""); | |
var offset = arrn.length % 3; | |
if (offset == 0) { | |
offset = 3; | |
} | |
var times = parseInt((arrn.length - 1) / 3); | |
for (var i = 0; i < times; i++) { | |
arrn.splice(i * 3 + offset + i, 0, ","); | |
} | |
$(this).val(M.prefix + arrn.join("") + M.getDigits(n)); | |
}, | |
unformat : function() { | |
if (DATA.editableView === false) { | |
return false; | |
} | |
M.config(this); | |
var strn = $(this).val(); | |
strn = strn.replace(new RegExp("[\\"+$.trim(M.prefix)+ "\\s,]", "g"), ""); | |
$(this).val(strn); | |
}, | |
config: function(obj) { | |
if ($(obj).data("prefix")) { | |
M.prefix = $(obj).data("prefix"); | |
} | |
if ($(obj).data("float")) { | |
M.floatFlag = $(obj).data("float"); | |
} else { | |
M.floatFlag = "off"; | |
} | |
}, | |
getDigits: function(n) { | |
if (M.floatFlag == "on") { | |
var f = parseFloat(n) - parseInt(n); | |
f = "" + Math.round(f * 100) / 100; | |
if (f == "0") { | |
f = "0.00"; | |
} | |
return f.substring(1); | |
} | |
return ""; | |
}, | |
filter: function(e) { | |
return e.keyCode >= "0".charCodeAt(0) && e.keyCode <= "9".charCodeAt(0); | |
} | |
}; | |
$(this).each(M.format); | |
$(this).on("keypress", M.filter); | |
$(this).on("blur", M.format); | |
$(this).on("focus", M.unformat); | |
return this; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
$(".price").money()