Say I have this custom Java class Club.java
:
public class Club
{
private Integer id;
private String name;
/* getters, setters */
}
Now the jquery-ui autocomplete code:
var autocomplete = $('#clubs').autocomplete({
source: currentClubs
}).data("autocomplete");
if (autocomplete != undefined)
{
autocomplete._renderItem = function(ul, item) {
return $("<li>").attr('data-value', item.value).append(item.label).appendTo(ul);
};
}
where currentClubs
is an array of JSON objects which correspond to the above Java class Club
( { value : club.id, label : club.name }
).
This works fine until I submit the form.
I am using Spring MVC Framework, here is my controller:
@RequestMapping(value = "someMapping", method = RequestMethod.POST)
public String someMethod(HttpSession session, Model model, @ModelAttribute("someForm") SomeForm form)
{
jada jada ...
}
where SomeForm
contains a field private Club clubChoice
. I would like to map my selected JSON Object to that field. How can I achieve this? Many thanks.
Well, it took me another 10 minutes to figure out how to do this.
I changed this part:
var autocomplete = $('#clubs').autocomplete({
source: currentClubs
}).data("autocomplete");
to this:
var autocomplete = $('#clubs').autocomplete({
source: currentClubs,
select: function (event, ui) {
$('#club-id').val(ui.item.id);
}
}).data("autocomplete");
where clubId
is a hidden input:
<form:input path="club.name" name="club-name" id="club-name" />
<form:hidden path="club.id" name="club-id" id="club-id" />