Sajjan Sarkar
Sajjan Sarkar

Reputation: 4198

onchange event does not fire when value is changed in onkeyup event

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.

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)

Upvotes: 6

Views: 6039

Answers (1)

luxcem
luxcem

Reputation: 1854

You can trigger events programmatically with jquery.trigger : http://jsfiddle.net/vHgst/5/

$(this).trigger('change');

Upvotes: 1

Related Questions