views:

761

answers:

1

I'm having trouble figuring out a way to conditionally cancel an asp:TextBox's OnTextChanged AutoPostBack using a javascript onchange event. I want to do this because it would be easy for me to check some conditions on the client side that would negate the necessity of doing a post-back.

I have something like this generated in the client HTML:

<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 this would either go ahead with the postback if DoMyCheck() returned true or cancel it if DoMyCheck() returns false. Apparently it cancels every time no matter what. Keep in mind that I simplified the long .NET IDs and the setTimeout() and OnKeyPress() stuff was autogenerated when i set AutoPostBack = true. The only code that I really put in 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 have to manually hook into internal .NET javascript to do the postback if I can help it.

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

+1  A: 

You are always returning, so postback never gets invoked. You should only return false (cancel the event) if your function returns false...

onchange="if(!DoMyCheck()) return false; setTimeout('__doPostBack(\'tb1\',\'\')', 0)"
Josh Stodola
You are exactly right--can't believe I missed that! Thanks for your help.
jakejgordon