Last active
May 12, 2017 08:28
-
-
Save guillaumepiot/6dafdd5bf048dd9994dac0c0decfba48 to your computer and use it in GitHub Desktop.
Augment text input to format currency - Duplicate origin field, format to currency display
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
// Author: Guillaume Piot, Alex Russell | |
// Copyright 2017 | |
// MIT License | |
var currency_fields = document.getElementsByClassName('form__text--currency') | |
function formatCurrencyField(elm){ | |
// Duplicate the element to create: | |
// - a hidden version with the integer value tp submitted to the form | |
// - a new text input to display the formatted value | |
var display_field = elm.cloneNode() | |
display_field.name = "" | |
// Make the original field hidden and without a class | |
elm.className = "" | |
elm.type = "hidden" | |
elm.parentNode.appendChild(display_field) | |
display_field.addEventListener('input', function(e){ | |
apply_formatting(elm, display_field, e.target.value) | |
}) | |
// Apply formatting on initial value if any | |
if(elm.value) { | |
apply_formatting(elm, display_field, elm.value) | |
} | |
} | |
function apply_formatting(hidden_field, display_field, value){ | |
var v = value.replace(/\D/g, "") | |
if(v) { | |
var values = int_to_currency(v) | |
hidden_field.value = values[0] | |
display_field.value = values[1] | |
}else{ | |
hidden_field.value = 0 | |
display_field.value = "" | |
} | |
} | |
function toLocaleStringSupportsOptions() { | |
return !!(typeof Intl == 'object' && Intl && typeof Intl.NumberFormat == 'function'); | |
} | |
function int_to_currency(value){ | |
// Reverse the value to count every 3 digits | |
var value_int = parseInt(value, 10) | |
if (toLocaleStringSupportsOptions) { | |
var value_formatted = value_int.toLocaleString('en-GB', {minimumFractionDigits: 0, maximumFractionDigits: 0, style: 'currency', currency: "GBP"}) | |
}else{ | |
var formatted_arr = [] | |
// Run a decremental loop to add the comma from the smallest digit | |
var length = value_int.length - 1 | |
for (var i = length; i >= 0; i--) { | |
if ((length - i ) % 3 == 0 && i != length) { | |
formatted_arr.unshift(',') | |
} | |
formatted_arr.unshift(value_int[i]) | |
} | |
var value_formatted = "£" + formatted_arr.join("") | |
} | |
return [value_int, value_formatted] | |
} | |
for (var i = 0; i < currency_fields.length; i++) { | |
formatCurrencyField(currency_fields[i]) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment