UpdatePanel and jQuery working together???

Ok, so you have a requirement where the user wants to auto populate certain fields based on some input they enter in a textbox.  Pop out your jQuery toolbox and get it done in few minutes, however when that textbox is inside of an UpdatePanel of a web forms project this simple task might leave you scratching your head as it did to me.  After countless hours here are the options and the solution that I came up with:

First I tried using the onTextChanged event which comes built in with every textbox control.  But the problem with this event is that it only gets fired when you move the focus away from the textbox by hitting the tab key for instance, which is not what I was after.  I wanted the event to fire as soon as it reaches certain length, in my case 5 for zip code value.  So after doing extensive research I ended up implementing the __doPostBack() event that the UpdatePanel itself uses and hence reap the benefits of the built in partial rendering on the UpdatePanel.

As you can see for this to work you’ll have to use two hidden fields that are outside of the UpdatePanel and then attach a trigger to the UpdatePanel for the hidden button’s click event.



And this button click event is what gets called when someone enters a zip code in the textbox.  This is a little trick that you have to do in order for this to work.



So now in my javascript section I have a function named AjaxUpdate which basically stores the value that’s being passed in from the jQuery function above and then initiates the trigger that we attached to the UpdatePanel by calling the  __doPostBack method. Certain things to keep in mind here is that the pageLoad event will be fired by the ScriptManager every time the page renders, whether it be full rendering or partial rendering in our case, that’s why I put the jQuery keyup funtion in there because it will get initialized every time that page loads.  I found this the hard way because first I tried using the jQuery ready function but since we’re dealing with partial page updates only the first keyup event fired after that it was no longer there.  Then I thought oh I’ll just attach a live event and then hook up the keyup, but again no success, so save the misery and just use the pageLoad which works great.  Second thing to keep in mind is that the ‘_’ before the doPostBack: there are two!

Now in you code behind file you could simply access the zip code values as such:



So after all this we have a working program that calls the hiddenButton_Click event using the __doPostBack method of the UpdatePanel using jQuery that we wrote inside of the pageLoad event of the ScriptManager, truly a mouthful.

Happy updating!! Open-mouthed smile