Click here to Skip to main content
15,893,564 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,

I have a textbox where date is entered and there is an onchange function to validate the date entered. But i want that onchange not to fire, if i click a particular button. Is it possible to prevent this?

Thanks
Arjun Menon
Posted

1 solution

The idea is simple: don't prevent events. Don't make your code overly complex and error-prone by registering and unregistering any events. Add all event handlers only once and never change them.

Instead, do much simpler thing: write the event handlers the way they do different things depending on some shared object used to control it. Simply put, have a shared flag object in the outer scope in relation to the handler functions. Then one handler, such as the click on your button, can modify this flag object to "don't handle onchange". The onchange handle will read this state and them simply return. This way, the onchange event will be invoked in all cases, but it will do nothing if the flag tells it so.

In simplest form, it could look like
JavaScript
var enableButton = //...
var disableButton = //...
var input = //...
var handleOnChange = true; //flag

disableButton.onclick = function() { handleOnChange = false; }
enableButton.onclick = function() { handleOnChange = true; }
input.onchange = function() {
	if (!handleOnChange) return;
	doSomethingOnChange();
}


Isn't that simple?

—SA
 
Share this answer
 
v3
Comments
Arjun Menon U.K 31-Jan-15 3:29am    
Hi Sergey,
I think the onchange is working first, bcs the cancel JS confirm is not coming. Anyway let me try :)
Thanks for the help.... :)
Sergey Alexandrovich Kryukov 31-Jan-15 3:39am    
What do you mean "working first"? I showed the order of adding handlers which is irrelevant. It has nothing to do with the order the events themselves are "working".

All you can see in this code sample is the assignment of the function objects to the properties "onclick" and "onchange". This is like assigning the value of 2 to one property of one object and the value of 3 to another, in the same thread. You should understand that the result does not depend on the order you do it.

Are you getting it?

—SA

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900