Search code examples
javascripthtmlstruts2struts

JS function included in the file is not getting invoked?


Javascript function included in history.js is not getting invoked in the Struts 2 jsp page when I select an item in the dropdown box.

This is the error I saw it in developer tools

Uncaught ReferenceError: getClasses is not defined
    at HTMLSelectElement.onchange (history.action:279)

This is how included in jsp page

<%@ taglib uri="/WEB-INF/struts-tags.tld" prefix="s"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<script type="text/javascript" src="<s:url value='/js/common/ajax.js'/>"/>
<script type="text/javascript" src="<s:url value='/js/common/sorttable.js'/>"/>
<script type="text/javascript" src="<s:url value='/js/common/CalendarPopup.js'/>"/>
<script type="text/javascript" src="<s:url value='/js/common/skuformatting.js'/>"/>
<script type="text/javascript" src="<s:url value='/js/common/formatsku.js'/>"/>
<script type="text/javascript" src="<s:url value='/js/history.js'/>"/>
<script type="text/javascript">
    var cal = new CalendarPopup();      
</script>
...
...
<td align="center"> 
    <s:select id="form.search.deptFilter"  property="form.search.deptFilter" 
     list="form.deptSelectList" onchange="getClasses()" size="5"
     listKey="name" listValue="value" headerKey="-1" headerValue="Select a Department" />
</td>
...

getClasses() is defined in history.js and here is the method definition inside that file.

...
    function getClasses(){
        var selectionComponent = document.getElementById('form.search.deptFilter');
        if(selectionComponent.options[selectionComponent.selectedIndex].value == -1)
            return;
        clearSubClasses();
        document.getElementById('form.search.classFilter').options.length = 0;  // Empty class select box
        sendAjaxRequest(selectionComponent,createClass);
    }
...

One thing I noticed in sources section of developer tools, I don't see all the js files included in the jsp page in js folder which I think is the problem but not sure why. But couple of weeks back, things were working fine.

Any idea why the js method present in the history.js file is not getting invoked?


Solution

  • The thing is your JSP page generate an invalid HTML. When loading it still invoke an order of it's elements. However <script> tags invoke in a separated thread by the browser asynchronously.

    And document loading doesn't wait for them to finish. Hense, you have not defined reference to the function because this function is not loaded yet. To make sure you define a function before you use it in the document you should use document ready event.

    The usual practice if you create a document with <head> and <body> tags, and put your <script> tags inside the <head>. All functions defined in the <head> are available to the <body> elements.