Reputation: 1141
I want to show the selected value in the dropdown on page load. My edit page shows a value, country. Now user belongs to USA, so USA should be selected by default on page load. I can use javascript or jquery.
I found few help on internet but they were with scriplets (<% %>) and I don't want to use them.
I am passing a List which has Id and Value. Also I have Id in another object. I can write the code by introducing a for loop in jsp and showing the value, but may be I am doing some mistake there. Also wanted to know if there is any better way to do this.
I am using Spring MVC.
Thanks.
Upvotes: 1
Views: 2798
Reputation: 3795
"Now user belongs to USA, so USA should be selected by default on page load.". You know before hand user belongs to some country.
Assuming you have a pojo Country as:
public class Country{
String countryName;
String countryId;
//setters and getters
}
public class YourForm{
List<Country> countryList;
String selectedCountryId;
...
//setters and getters
}
In your controller method which delegates to the jsp:
...
YourForm form = new YourForm();
//set your countrylist to form
//set country user belongs to - selectedCountryId - since you know before hand user belongs to some country.
model.addAttribute("yourForm", form):
...
Now access it in jsp as:
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=windows-1252">
</head>
<body>
<form:form id="yourForm" modelAttribute="yourForm" method="post">
<tr>
<td width="50%" class="label">
<form:select id="countryId" path="selectedCountryId" title='Select Country'>
<option value="">Please Select</option>
<form:options items="${countryList}" itemValue="countryId" itemLabel="countryName"/>
</form:select>
</td>
</tr>
</body>
Since selectedCountryId is already set in controller you will see that country as auto selected in the jsp.
Upvotes: 5