customd / jquery-number

Easily format numbers for display use. Replace numbers inline in a document, or return a formatted number for other uses.
https://www.customd.com/articles/14/jquery-number-format-redux
MIT License
442 stars 402 forks source link

Deletes entire number instead of decimals when over a 1000 #130

Open SergioReis97 opened 7 years ago

SergioReis97 commented 7 years ago

I'm having quite a hard time trying to understand why this is happening

Using this to activate $('#myNumberInput').number(true, 2, ',', '.');

and this to preview $("#myNumberInput").keyup(function(){ console.log($(this).val()); });

Everything works pretty much as expected most of the times, except when a value is over 4 digits and 2 decimals. When I try to backspace the last decimal, everything is deleted. For example:

1 10 100 1000 1000.2 1000.23 //-> Backspace next 0 //EXPECTED WAS 1000.20 OR 1000.2

https://gyazo.com/05678b909df3b79209c564d6ac3b5464

SergioReis97 commented 7 years ago

Well, this is a temporary/permanent solution. I did other stuff while waiting to see if this was fixed but since the schedule was tightening I was forced to fix it.

Didn't want to stop using the plugin and do everything manual so I did a workaround. This is nowhere near optimal solution I know. For my case I ended up changing the plugin code. `// If hitting the backspace key, and the cursor is to the right of the decimal // (but not directly to the right) we replace the character preceding the // caret with a 0. else if (decimals > 0 && code == 8 && start > this.value.length - decimals) { if (this.value === '') return;

                        // If the character preceding is not already a 0,
                        // replace it with one.
                        /*if (this.value.slice(start - 1, start) != '0') {
                            val = this.value.slice(0, start - 1) + '0' + this.value.slice(start);
                            // The regex replacement below removes negative sign from numbers...
                            // not sure why they're necessary here when none of the other cases use them
                            //$this.val(val.replace(regex_dec_num,'').replace(regex_dec,dec_point));
                            $this.val(val);
                        }

                        e.preventDefault();*/
                        data.c--;

                        // Set the selection position.
                        setPos = this.value.length + data.c;
                    }`

From lines 343, added that comment on the if and it does exacly what I inteded. Great coding, awesome comments so it was easy getting there to do a quickfix. Thanks