简体   繁体   中英

Set input value in keyup, stops change event from firing

NEW Fiddle: http://jsfiddle.net/martinnormark/jBZfs/14/ - new isolated example. See how the change event is not fired for Amount 2! **

I have a jQuery plugin for formatting a number in a currency format, as you type.

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

The problem is, if you enter a value of at least 4 digits (causing the need to thousand separator: 1178 becomes 1,178), the change event dies. As long as you stay below 4 digits, not causing a new format, the change event is fired.

In the fiddle, try to enter 12, then 123. You should see a text reading 'change event raised'. And then enter 1234 - and the change event is not fired.

This will have something to do with the manipulation of the input element's value 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 full source, see the file on Github: https://github.com/martinnormark/jquery-format-currency/blob/master/src/jquery.formatcurrency.js )

The question is , if there's a way to make sure the change event will be fired?

UPDATE - Current state in browsers
Chrome : Change event fired, if number is below 4 digits.
Safari, IE : Change event is never fired, as long the value is set programmatically. Enter letters instead of numbers will trigger the change event.
Firefox : Works!
Opera : Works!

The easiest way would be, to trigger the change event from within the keyup function:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM