5

OVERVIEW:

I'm writing a jquery plugin which converts a textbox into a time entry box. Meaning it allows the user to enter time in HH:MM format. Part of this process is to insert a colon (:) at the right place. On keyup i check if the user has typed 2 numbers and if so append a colon to the entered value.

PROBLEM:

This approach works fine except when someone applies the plugin on the textbox but also wants to have a custom onchange handler.This onchange handler does not fire when the code updates the textbox value programmatically nor does it fire when the textbox loses focus.

MY UNDERSTANDING:

I'm guessing here, so please correct me if I'm wrong.

  • Maybe the textbox has an internal "_value" (underscoring to differentiate from the public value attribute) field which holds the value in the textbox before the edit begins. When the focus leaves the texbox, the JS engine checks if the current value of the textbox matches the "_value" of the textbox.If they are different, the onchange event is fired.
  • Perhaps value changes using regular native keystrokes dont modify "_value" just the value, so the onchange gets fired. But perhaps value changes made via JS modify both the value and the "_value" and so the onchange event does not fire?

WORKAROUNDS:

The blur event fires as it has nothing to with the value. So I can explicitly fire the change event from the blur event.But I dont want to do this as it is a hack and breaks the semantics of blur and change.

RELATED LINKS:

I found several links on SO with the same question but no answer (IMHO) gives an elegant or correct solution. here are some of the ones I saw:

SIMPLIFIED CODE:

$(document).ready(function () {
    $("input").keyup(function () {
        this.value = '*' + this.value;
        // this changes the value, but does not fire the onchange event
        // and it also does not fire it when the textbox loses focus.
        // blur fires though.
    });
    $("input").change(function () {
        alert('in change');
    });

    $("input").blur(function () {
        alert('in blur');
    });
});

FIDDLE:

http://jsfiddle.net/sajjansarkar/vHgst/4/

BROWSERS TESTED: IE8,10 and Chrome. Works in FireFox(!!) (+1 Felix Kling)

4

1 回答 1

1

您可以使用 jquery.trigger 以编程方式触发事件:http: //jsfiddle.net/vHgst/5/

$(this).trigger('change');
于 2013-08-20T16:21:58.380 回答