Thursday, April 18, 2013

Spring: Java dynamically change select box options with ajax and jquery

First define the select box in JSP:

<form:select path="contactPhoneNumber" id="contactPhoneNumber">
<form:option value="" label="<Choose contact>"/>
<form:options items="${contactList}" itemLabel="fullName" itemValue="phoneNumber"/>

Define a JS to call the backend:
function updateContactList() {

$.ajaxPrefilter(function (settings, localSettings, jqXHR) {
var tok = $('input[name=CSRFToken]').val();
jqXHR.setRequestHeader("CSRFToken", tok);

dataType: "json",
url: "/updateurl",
type: 'POST',
success: function (result, textStatus) {

cb = '';
$.each(result, function (i, data) {
cb += '';

$('#contactPhoneNumber option:gt(0)').remove();

error: function (xhr, ajaxOptions, thrownError) {

$('#contactPhoneNumber option:gt(0)').remove();


Now create the controller method:
@RequestMapping(value = "/updateurl", method = RequestMethod.POST)
public String updateContactList(@ModelAttribute("orderForm") OrderForm orderForm,
BindingResult result, ModelMap model) {

// Note that the Contact object has member variables 
// fullName and phoneNumber
// and gettters and setters for each

List<Contact> contactList = fillInTheContacts();

return new Gson().toJson(contactList);


Thats it. When the JSON string is returned to the AJAX call, it parses it out in the .each loop and injects the HTML into the page using jQuery

So now your select box options should automatically be updated.

1 comment:

  1. Can we please get the full code for this example?