Tuesday, December 2, 2008

Calling Action on OnChange event of Drop Down List with Struts2

Last week I was having problem with drop down onchange event on strut project. I wanted to load some data to Drop down list according to another item in a drop down list when it is changed. Finally I found this way as the solution with JavaScript. Within the JSP page can be called any Struts Action using JavaScript function. I have mentioned some of sample code regarded to all steps.


Class Diagram for the scenario:-


Code sample for “VIEW” (createSchedule.jsp):-

---- JavaScript Code ----

<script type="text/javascript">

function onTypeChange() {

document.scheduleForm.action = 'loadCourcesForType.action';

document.scheduleForm.submit();

}

</script>

---- HTML Code ----

<s:select name="sch.course.courseTypes.typeId"

list="#session.crsTypes"

listKey="typeId"

listValue="typeName"

onchange="onTypeChange()" />

<s:select name="sch.course.courseId"

list="#session.courses"

listKey="courseId"

listValue="courseName" />


Code sample for STRUTS XML:-

<action name="loadCourcesForType"

method="loadCoursesForType"

class="com.abc.struts.action.ScheduleAction" >

<result name="success"&gt createSchedule.jsp </result&gt

</action>


Code sample for ACTION class (ScheduleAction.java):-

public String loadCoursesForType() {

// Load Courses to Session

courses = get courses due to the selected course type (as sch.getxxx(selected_type))

session.put("courses", courses);

return "success";

}

1 comment:

Unknown said...

Thanks man. Was useful for my project.