Reputation: 1653
I have a dropdown list in javascript which is populated based on the 'name' field of an object. Is it possible to put the whole object in the dropdown list and just display the name? The reason im asking is because I want to change the value of another dropdown based on what the user selects, and that information is already available in the first object (before I strip out just the name).
So at the moment I have this (Java controller):
List<String> hostsList = new ArrayList<String>();
for (Client client : adminService.getClients()){
hostsList.add(client.getName());
}
result.put("hostsList", hostsList);
and then this on the javascript side:
<form:form id="iForm" method="post"
action="${pageContext.request.contextPath}/host"
commandName="hostsForm">
<td valign="top">Hosts:</td>
<td valign="top"><form:select path="uSetHostName">
<form:option value="NONE" label="--- Select ---" />
<form:options items="${hostsList}" />
</form:select>
</td>
So how do I put a whole object into the dropdown and just display its name?
Thanks,
Upvotes: 1
Views: 2336
Reputation: 3241
You're asking for a Java object to be converted into a JavaScript object, as far as I can tell, so that you can use that object later in JavaScript to drive dropdown values.
There are a couple ways of doing this. The first way is just to represent each Java Client
object as a JavaScript object, then populate both drop downs in JavaScript. This might be easiest using some kind of JSON library like Gson or Jackson. Here's an example using JQuery and Gson:
<script lang="text/javascript">
var clients = <%= new Gson().toJson(clients) %>;
// Fill the first dropdown.
$("#myDropdown").empty();
$.each(clients, function() {
$("<option/>").attr("value", this.id).text(this.name).appendTo("#myDropdown");
});
$("#myDropdown").on("change", function(event) {
var selectedClientId = $("#myDropdown").val();
var client = $.grep(clients, function(client) {
return client.id = selectedClientId;
});
$("#myOtherDropdown").val(client.someOtherValue);
});
</script>
...
<select id="myDropdown" name="..."></select>
...
<select id="myOtherDropdown" name="..."></select>
The second way is to do exactly what you're doing right now, and then put just the minimal amount of the Client
objects that you need to populate the other dropdown into the JavaScript code. That would look something like this:
<script lang="text/javascript">
var clientIdToOtherValueMap = {
<%
for (Client client : clients) {
%>
'<%= client.id %>': '<%= client.otherDropdownId %>',
<%
}
%>
'': ''
};
// Fill the first dropdown.
$("#myDropdown").on("change", function(event) {
$("myOtherDropdown").val(clientIdToOtherValueMap[$("#myDropdown").val()]);
});
</script>
...
<select id="myDropdown" name="..."></select>
...
<select id="myOtherDropdown" name="..."></select>
Hopefully that helps get you started!
Upvotes: 1