'How can I react to 'onchange' and 'aspx state' information for a form dropdown?

I'm after what seems to me to be a straightforward pattern for handling page refreshes when I've got a drop-down that reacts to the onchange event.

I've used the following in the vb code behind (in the Load handler):

MyDropDown.Attributes.Add("onchange", "ProcessDDChange(this.value);")

Function ProcessDDChange() is in-page JavaScript that grays out some other form inputs for certain values of the drop down.

This works fine, but after a postback, onchange is apparently not fired when the previous state is restored, so disabled boxes are enabled again.

I've investigated load events (page and drop-down), but both fire too early to be of use and I can't see any later options.

Is there a standard way of doing this? I need a hook for running a js function post DOM setup, post asp state restore.

Info

I'm using .net 3.5 and I'm looking for a cross browser solution. This is not my project, so I can't add jQuery (much as I'd like to) or other libs.



Solution 1:[1]

You could wrap the dropdown in an update panel and set the trigger for the change event like epascarello suggests. Have you tried adding it to the markup like

 <asp:DropDownList runat="server" ID="MyDropDown" onchange="ProcessDDChange(this.value);"></asp:DropDownList>

EDIT:

So you are loosing the onchange listener when you postback, the above example should preserve it. But if not you could also try this in the codebehind event that you would like to have call the ProcessDDChange: for vb.net

  ScriptManager.RegisterClientScriptBlock(Me, Me.GetType(), "err", "ProcessDDChange(this.value);", true);

FINAL EDIT:

Thanks for sticking it out with me Bob, while I was attempting to understand the question: The document.ready event is raised after the PageLoad event is complete and the DOM is constructed. This would be the proper place to call your ProcessDDChange().

  document.addEventListener("DOMContentLoaded", function(event) { 
      ProcessDDChange(ddlId.selectedValue);
    });

Solution 2:[2]

onchange does not fire when the page loads. You would need to trigger the function on page load OR you need to have the server set up the page correctly from the start.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 epascarello