0

I use the plugin jQuery Number Format to dynamically format numbers for both "," decimal and "." format. This works well on normal events. The issue I have is with dynamically added HTML, in which you use a delegate to fire the jQuery.

Normal

$('input.number').number( true, 2 );

If I use another ID that exists at runtime, such as #body, what is the proper way of calling it? I tried something like

$("#body").on("keyup", "input#number", function(event) {
    $(this).number(true,2,',','.');
 });

but it has problems with numbers on the right side of the decimal point. For instantance, if I try and type "450,45", the last hundreds digit is never used, additional numbers I type are placed in the 10s place.

Is there a proper way to do this?

1 Answers1

0

As I understand it, the input should always be something like 123.456 and the fourth parameter is not another possible decimal separator for the input but the output's thousand separator.

$("#body").on("change", "input#number", function(event) {
    // replace , by .
    var value = $(this).val().replace(",",".");
    // update input value 
    $(this).val($.number(value,2,',','.'));
});

The best way to do it, is to force the user to give a valid input with a validation. You will then avoid having to find such work arounds to format your numbers. Here is more information: https://jqueryvalidation.org/number-method/

TheDeveloo
  • 413
  • 4
  • 13
  • I did what you suggested, but had the same problem. I added a console.log(value) after your value statement, and I noticed that if I type "85", the two logs were "8" and then "8.005". – Edwin Rooks Dec 11 '19 at 21:55
  • Okay, your need to use the change event instead of keyup because when you type 8, the value of your input is replaced by 8.00 then you type 5 and here you are with 8.005. Another solution would to [move the caret right where you typed](https://stackoverflow.com/questions/512528/set-keyboard-caret-position-in-html-textbox) but that will need some calculation (i.e. when typing 4 digits numbers). – TheDeveloo Dec 11 '19 at 22:24