Please bear with me as I am new to jQuery, and JEE and am not a programmer :-) I have followed a number of tutorials on how to dynamically populate a dropdown box; however I can not get it to work.
I want to select a State and populate the Region drop down based on that selection (each State is made up of Regions).
My issue is with the call to the java and return of values.
So far I have (mashed up from a number of tutorials) the following:
HTML
<div class="row">
<div class="col-md-6">
<div class="form-select-group">
<label for="selectState">Select State:</label>
<select class="form-control" id="selectState">
<option value="" disabled selected>Select your State</option>
<option>ACT</option>
<option>NSW</option>
<option>NT</option>
<option>QLD</option>
<option>SA</option>
<option>TAS</option>
<option>VIC</option>
<option>WA</option>
</select>
</div>
</div>
<div class="col-md-6">
<div class="form-select-group">
<label for="selectRegion">Select Region:</label>
<select class="form-control" id="selectRegion">
<option>Please select your State first</option>
</select>
</div>
</div>
</div>
jQUERY
$(document).ready(function(){
$('#selectState').on('change', function() {
//do something here
//alert($("#accountName").val());
$.ajax({
type: "POST",
url: "RegionView",
cache: false,
data: $(selectState).serialize(),
success: function(data){
$('#ajaxGetUserServletResponse').text(data);
}
}).done(function(response) {
// Clear options
$("#selectRegion").find("option").remove();
// Loop through JSON response
$.each(response, function (index, value) {
$('#selectRegion').append($('<option>', { value: value.name }, '</option>'));
})
});
});
});
JAVA
package client;
import java.io.IOException;
/**
* The purpose of this View is to return a list of Regions associated with a selected State.
*/
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import server.MySQLConnection;
@WebServlet("/RegionView")
public class RegionView extends HttpServlet {
private static final long serialVersionUID = 1L;
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String state = request.getParameter("selectState"); // From bootstrap
response.getWriter().write("Here " + state);
MySQLConnection.getConnection();
List<String> listRegions = MySQLConnection.listGroupRegions(state);
if (listRegions == null || listRegions.isEmpty()) {
response.getWriter().write("Please select a State");
}else{
response.getWriter().write("State found");
request.setAttribute("selectRegion", listRegions);
}
}
}