I have an input box that takes a number that gets verified in function opConfig.reloadPrice(). I set 2 observers one the same element, on ‘change’ it executes the code when I click outside the box or use tab-if the change has been made. On ‘keypress’ it checks if the return key was pressed then executes the code AND it also triggers the ‘change’ observer!! So in this case the function opConfig.reloadPrice() gets executed twice (and I end up with two identical alert boxes).
The code that I have now:
<input type="text" value="" name="options[1]" id="options_1" onkeypress="return disableEnterKey(event)">
Event.observe($('options_1'), 'change', function(e){
opConfig.reloadPrice();
});
Event.observe($('options_1'),'keypress', function(e){
if (e.keyCode == Event.KEY_RETURN)
opConfig.reloadPrice();
});
I’ve tried several different solutions (I’ve tried ‘blur’ event, putting one observer in the other… )
I’m looking for a solution similar to this one
jQuery-Two events at the same time
Thanks a million
EDIT-Solved:
Thanks to katspaugh I solved this. There were few things that were not clear to me, one of them is: ‘keypress’ event is observed before ‘change’ event, which is why you can set variables in one observer and check them later in another (this is also why it took me a while to understand katspaughs code 🙂 ).
Anyway, I change the code a bit that it suits me:
var enterPressed = 0;
Event.observe($('options_1'), 'change', function(){
if (enterPressed !== 1) {
opConfig.reloadPrice();
}
enterPressed = 0;
});
Event.observe($('options_1'), 'keypress', function(e){
if ((e.keyCode == Event.KEY_RETURN) || (e.keyCode == Event.KEY_TAB)) {
enterPressed = 1;
opConfig.reloadPrice();
}
else
enterPressed = 0;
});
Cheers,
jazkat
Save the current value of the input field in an upper-scope variable (up-value).
If the value changes in one of the events, fire the handler and update the upvalue:
Also, you’d better remove the inline listener in HTML (and never add them again):
Demo.