Search code examples
javascripthtmljspstruts-1

onChange event not working when change automated


I have an onChange event on one select box (usageDisplays), which populates the next select box based on the selected value of the first:

<html:select name="usageDisplays" property="name" indexed="true" onchange='<%="populateYearsList(" + Id + "," + name + ")"%>' />

This works fine when the user selects the value in usageDisplays, but doesn't work at all when the value of usageDisplays is set based on a radio button choice earlier on the page

getElementByName("usageDisplay.name").value = userName;

Solution

  • hi onchange will fire only when the select value must change but on page load it will not select anything first and then change

    Programmatically changing the value doesn't fire a change event, that only occurs if the user focuses the element, changes the value and then puts focus elsewhere.

    Options are to manually call the onchange listener, dispatch a change event on the element, or manually bubble the change event by going up the DOM looking for parents with an onchange listener and calling them.

    Here is an answer that seems to fit the bill: trigger onchange event manually

    Some links:

    MDN dispatchEvent (standards compliant): https://developer.mozilla.org/en/DOM/element.dispatchEvent
    MSDN fireEvent (IE proprietary): http://msdn.microsoft.com/en-us/library/ie/ms536423(v=vs.85).aspx