I have failed to convert the input value to currency format. I want to automaticly add thousands and decimal separators when the user types the number (5,000.00; 125,000.00).
Here's my code :
$('input.CurrencyInput').on('blur, focus, keyup',
function() {
$(this).val().toLocaleString('en-US', {
style: 'decimal',
maximumFractionDigits: 2,
minimumFractionDigits: 2
});
});
There are a couple of problems with your code:
toLocaleString
on it.Correcting these, here is a working demo. For the sake of simplicity, I've removed the other event handlers, except blur
, as keyup
was causing problems.
$('input.CurrencyInput').on('blur', function() {
const value = this.value.replace(/,/g, '');
this.value = parseFloat(value).toLocaleString('en-US', {
style: 'decimal',
maximumFractionDigits: 2,
minimumFractionDigits: 2
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input class="CurrencyInput">