Sunday, 10 May 2015

spring mvc dropdown onchange example

spring mvc dropdown onchange example

In Spring controller , write below code to bind the <form:select />, <form:option /> or <form:options />, we will use bellow value to render HTML form:select box :

@Controller

@RequestMapping("/")

public TestController{

protected ModelAndView createSelectWithValue(HttpServletRequest request) throws Exception { 
 
        Map cData = new HashMap(); 
 
        Map<String,String> countryList = new LinkedHashMap<String,String>(); 
 
        countryList.put("TX", "Texas");
 countryList.put("IN", "India");
 countryList.put("NY", "New York");
 countryList.put("NJ", "New Jessy");
 cData.put("cList", countryList); 
  
        ModelAndView mav=new ModelAndView();
        mav.addAttribute("selectedCountry","IN"); 
        mav.addAttribute("cList",cData);
        mav.setView("index");
  
        return mav;
  }
}
 
 
index.jsp
 
1) javascript which we will call onchange of spring mvc dropdown (<form:select />)
  
 <script type="text/javascript">

 function getValue(obj)
 {
  alert("You have selected Country: " + obj.value);
 }
 
</script>
 
2) spring mvc dropdown with onchange event
 
   <select id="country" name="country" onchange="getValue(this);"> 
 
      <option value="">--select country--</option>
 
      <c:forEach items="${cList}" var="name"> 
 
            <option value="${name[0]}" >${name[1]}</option>
        
      </c:forEach>
  </select>