Using Javascript OnChange event to conditionally cancel AutoPostBack in a text field

I'm having trouble finding a way to conditionally cancel asp: TextBox OnTextChanged AutoPostBack using the jchange event. I want to do this because it would be easy for me to check some conditions on the client side that would deny the need to make feedback.

I have something like this generated in an HTML client:

<input name="tb1" type="text" onchange="return DoMyCheck(); setTimeout('__doPostBack(\'tb1\',\'\')', 0)" onkeypress="if (WebForm_TextBoxKeyHandler(event) == false) return false;" id="tb1"/> <script type='text/javascript'> function DoMyCheck() { if(something) { return false; }else { return true; } } </script> 

I thought that if DoMyCheck () returned true or canceled it, DoMyCheck () would return false. Apparently, it cancels every time, no matter what. Keep in mind that I simplified the long .NET identifiers, and the setTimeout () and OnKeyPress () files were auto-generated when I set AutoPostBack = true. The only code I really put there was the onchange event.

I saw one solution posted here: http://www.eggheadcafe.com/community/aspnet/3/10042963/try-this.aspx

but this is unacceptable in my mind because I do not want to manually connect to the built-in javascript.NET to do the postback if I can help.

Does anyone have a better solution? I really appreciate any help you can give.

+4
source share
1 answer

You always come back, so postback is never called. You should only return false (cancel the event) if your function returns false ...

 onchange="if(!DoMyCheck()) return false; setTimeout('__doPostBack(\'tb1\',\'\')', 0)" 
+4
source

All Articles