Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

  • 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:

  • Javascript : onchange event does not fire when value is changed in onkeyup event

  • https://stackoverflow.com/questions/14410870/using-both-onchange-and-onkeyup-in-ie8

  • Javascript: "onchange" event does not work with "value" change in "text input" object

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)

like image 701
Sajjan Sarkar Avatar asked Nov 11 '22 23:11

Sajjan Sarkar


1 Answers

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

$(this).trigger('change');
like image 154
luxcem Avatar answered Nov 15 '22 00:11

luxcem