$(\'input#not-gonna-work\').bind({
keyup: function(){
console.log(\'Typed a key\');
$(this).val($(this).val() + \'.\');// try with any other char
That seems to be the behavior to me.. If the value of an element is changed via script then your onchange will not be triggered. In such cases you need to save the value onfocus
and check the value onblur
and trigger onchange
manually.
See below,
DEMO: http://jsfiddle.net/vCxme/6/
$('input#not-gonna-work').bind({
keyup: function(){
console.log('Typed a key');
$(this).val($(this).val() + '.');
},
change: function(){
console.log('I\'m a changed input');
},
focus: function ( ){
$(this).data('orig_value', $(this).val());
},
blur: function () {
if ($(this).val() != $(this).data('orig_value')){
$(this).change();
}
}
});
$('input#gonna-work').bind({
keyup: function(){
console.log('Typed a key');
},
change: function(){
console.log('I\'m a changed input');
}
});
The above implementation is from pseudo code as from FF onChange
Note: The browser change event will not be triggered when the value is changed via script.
I tried it in IE9 and it has the same behavior as Chrome.
I don't think it's a bug.
Using .val(value) on an HTML element will reset the "manually changed" flag and thus no change event will occur (because the user doesn't change anything manually AFTER the val() operation).
I would approach from a slightly different angle (so work around), of checking the value of the field every time a keyup event is performed. See http://jsfiddle.net/vCxme/3/
This looks like a valid Chrome bug. My guess is that changing the value resets whatever Chrome relies on to trigger the onChange
event since the user last focused on the input. I would suggest using a workaround (unfortunately) that should work in all browsers.
I've updated your code with such an example here. The idea is that you store the original value when the input receives focus, then compare the original value to the updated value when the input is blurred. If it is a different value, then perform the same logic that you would have put into your change callback.
It seems this behavior is expected. (See http://dev.w3.org/html5/spec/common-input-element-apis.html#event-input-change).
It mentions that if you programmatically change the value, you have to manually fire the event.
And according to https://developer.mozilla.org/en-US/docs/DOM/element.onchange, Mozilla implements change as follows:
control.onfocus = focus;
control.onblur = blur;
function focus () {
original_value = control.value;
}
function blur () {
if (control.value != original_value)
control.onchange();
}
For now, you can capture the blur event and fire 'change' event from there. (You may want check your before and after values before calling change() as done by Mozilla.)
blur: function(){
$(this).change();
}