Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
63
rated 0 times [  65] [ 2]  / answers: 1 / hits: 27079  / 6 Years ago, wed, june 6, 2018, 12:00:00

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
});
});

More From » jquery

 Answers
23

There are a couple of problems with your code:




  1. You're using comma when binding multiple event handlers to the input box.

  2. You're not converting the received value to a number before applying toLocaleString on it.

  3. You're not setting the value of the textbox again after conversion.



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>




[#54263] Friday, June 1, 2018, 6 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
ariel

Total Points: 523
Total Questions: 111
Total Answers: 100

Location: Anguilla
Member since Sun, Jan 29, 2023
1 Year ago
;