Set input value in keyup, stop change event from firing

NEW Fiddle: http://jsfiddle.net/martinnormark/jBZfs/14/ - a new isolated example. See how the change event does not fire for sum 2! **

I have a jQuery plugin to format a number in currency format as I type.

You can see this in action in this script: http://jsfiddle.net/martinnormark/Rv4Ug/1/

The problem is that if you enter a value of at least 4 digits (which results in the need for a thousands separator: 1178 becomes 1,178), the change event dies. If you remain below 4 digits without causing a new format, the change event is fired.

In the violin, try typing 12, then 123. You should see a text reading "change event raised." And then enter 1234 - and the change event will not be fired.

This will have to do with manipulating the value of an input element in a keyup event handler:

$this.on("keyup.autoformatcurrency", function(event) { if ($.inArray(event.keyCode, keyCodes) > -1) { formatCurrency($(this), true); } }); 

And the formatCurrency function:

 function formatCurrency($this, setCaretPosition) { var rawValue = $this.val(), floatValue = Globalize.parseFloat(rawValue); if ($.isNumeric(floatValue)) { var formattedValue = Globalize.format(floatValue, settings.formatString), caretPosition = 0; if (setCaretPosition) { caretPosition = $this.caret().end + (formattedValue.length - rawValue.length); } $this.val(formattedValue); if (setCaretPosition) { $this.caret(caretPosition, caretPosition); } } } 

(for the full source, see the file on Github: https://github.com/martinnormark/jquery-format-currency/blob/master/src/jquery.formatcurrency.js )

Question , if there is a way to make sure that the change event will be fired?

UPDATE - current state in browsers
Chrome : change the event if the number is less than 4 digits.
Safari, IE : The change event never fires because the value is set programmatically. Entering letters instead of numbers will result in a change event.
Firefox : it works!
Opera : it works!

+4
source share
1 answer

The easiest way is to trigger a change event from the keyup function:

 $this.on("keyup.autoformatcurrency", function(event) { if ($.inArray(event.keyCode, keyCodes) > -1) { formatCurrency($(this), true); $(this).change(); } }); 
0
source

Source: https://habr.com/ru/post/1384656/


All Articles