Created
February 6, 2015 15:40
-
-
Save cpoDesign/8788cb6621b64c45285c to your computer and use it in GitHub Desktop.
Currency formatting in input
This file contains 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
<input type="text" class="inputNumber" value="123456789" /> | |
<input type="text" class="inputNumber" value="123456789" /> | |
<button>click</button> |
This file contains 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
$(document).ready(function() { | |
$('button').click(function(){ | |
$('input.inputNumber').each(function () { | |
var value = $(this).val(); | |
if (!value || value.length == 0) { | |
return value; | |
} | |
value = value.toString(); | |
value = value.replace(/[^0-9\.]/g, ""); | |
$(this).val(value); | |
}); | |
}); | |
// on loading the form apply formatting | |
$('input.inputNumber').each(function() { | |
applyFormatting($(this)); | |
}); | |
function numberWithCommas(value, addExtraZeros) { | |
if (addExtraZeros == undefined) | |
addExtraZeros = false; | |
value = value.toString(); | |
value = value.replace(/[^0-9\.]/g, ""); | |
var parts = value.split('.'); | |
if (parts.length > 0) { | |
parts[0] = parts[0].replace(/\d{1,3}(?=(\d{3})+(?!\d))/g, "$&,"); | |
if (parts[1] && parts[1].length > 2) { | |
parts[1] = parts[1].substring(0, 2); | |
} | |
if (addExtraZeros && !parts[1]) { | |
parts[1] = "00"; | |
} | |
else if (addExtraZeros && parts[1] && (parts[1].length === 1)) { | |
parts[1] = parts[1] + "0"; | |
} | |
else if (!addExtraZeros && parts[1] && (parts[1] == "00")) { | |
parts.splice(1, 1); | |
} else if (!addExtraZeros && parts[1] && (parts[1].length === 1)) { | |
parts[1] = parts[1] + "0"; | |
} | |
} | |
return parts.join("."); | |
}; | |
function applyFormatting (element) { | |
var value = element.val(); | |
var original = value; | |
if (!value || value.length == 0) { | |
return; | |
} | |
value = numberWithCommas(value); | |
if (value != original) { | |
element.val(value); | |
element.triggerHandler('input'); | |
} | |
}; | |
$('input.inputNumber').bind('keyup', function (event) { | |
applyFormatting($(event.target)); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment