(using jQuery 1.4.4 edition)
The title of the question might not be that clear, that is why I am going into a more detailed description below:
I am trying to trigger some JavaScript code when a selection in one of my select boxes changes. I know that I can do that with the change() as follows:
var my_handler = function(eventObject){
// ... do something here ...
};
$('#my_select_box').change(my_handler);
The problem is that this is not triggered when user changes selection by keyboard. I searched in Stack Overflow and everybody is suggesting to bind the same handler on keyup event too, as follows:
var my_handler = function(eventObject){
// ... do something here ...
};
$('#my_select_box').change(my_handler).keyup(my_handler);
Indeed, both when I change the selection by keyboard and when I change the selection by mouse the handler is executed.
The problem is when I change the selection with keyboard and then I move on to the next field (either by mouse or keyboard) in the form. The handler is triggered again (second time)
Can you explain why does this happen and tell me whether there is a way to bypass this problem?
The only answer that seems to work is to keep track of the actual change of your value in some way, like a variable outside the event handler. You may not be able to avoid raising the event, but you can choose not to respond to it. The example below illustrates: