I'm working on a project and I'm trying to do a cascade dropdown using ajax.
I managed to do the implementation but I don't know how to pass the selected id from the second dropdown to a controller using thymeleaf in order to show the information about the selected airport.
So, this is the script:
function retrieveAirports() {
$.ajax({
url: '/countries/airports?countryId=' + $('#countrySelect option:selected').val(),
type: 'get',
contentType: 'application/json',
success: function (result) {
var $dropdown = $("#airportSelect");
var $id = $("#airportId");
$dropdown.empty();
$.each(result, function() {
$dropdown.append($("<option/>").val(this.id).text(this.name));
});
},
error: function () {
// what do you want to do in case of error
}
});
}
And this is the implementation of the dropdown. First, we have the country dropdown
<select id="countrySelect" onchange="retrieveAirports()">
<option selected value="-1"></option>
<option th:each="country : ${countries}" th:value="${country.id}" th:text="${country.name}">Option</option>
</select>
And this one is the airport dropdown, the result of this one depends on the id that was passed from the first one to the script.
<form th:action="#{/airport}" method="post" th:object="${airportSelect}">
<select id="airportSelect">
<option selected value="-1"></option>
</select>
<input type="submit" value="Send"/>
</form>
Can someone please help me?
Thank you!
Add a name to the airport selector, for example airport:
<form th:action="#{/airport}" method="post" th:object="${airportSelect}">
<select id="airportSelect" name="airport">
<option selected value="-1"></option>
</select>
<input type="submit" value="Send"/>
</form>
And then, when you click the submit button, the Spring controller for the path /airport will be called with airport as a POST parameter. For example:
#Controller
public class AirportController {
#PostMapping("/airport")
public View viewAirport(#RequestParam("airport") int airport) {
// ...
}
}
Related
If I write a Spring MVC Controller, how can I display the DBData in my HTML file.
e.g. I have db.table called Setting and I want to display the IDs from that table in my HTML file as a Dropdown list.
#Controller
public class CustomChannelController {
private Setting setting;
private Diagram diagram;
private Channel channel;
#RequestMapping(value = "/customchannel", method = RequestMethod.GET, produces = "application/json; charset=utf-8")
public #ResponseBody Setting getId() {
return this.setting;
}
<table>
<tr>
<td>
<label class="col-md-12 control-label"> <%=language['UI.reportSetting.channel']%> : </label>
</td>
<td>
<select id="selectReportChannel" class="form-control">
<option value="0" ><%=setting[ID]%></option>
</select>
</td>
</tr>
</table>
Well it depends on how you retrieve data... do you use AJAX calls? Or do you need them when page is loaded?
Let's see the 2 scenarios
Note: in boths scenarios we assume you are returning a list of object like this:
public class Option{
private String value;
private String text;
//getter and setter
}
AJAX CALL: for this I assume we are using JQuery; in this case you will have in your JS or JSP file something like this:
$.ajax({
url : 'customchannel',
dataType : 'json',
contentType : 'application/json; charset=UTF-8',
type : 'GET',
success : function(items) {
$.each(items, function (i, item) {
$('#selectReportChannel').append($('<option>', {
value: item.value,
text : item.text
}));
});
},
error : function(data) {
}
});
<select id="selectReportChannel" class="form-control">
</select>
Page loaded In this case in your controller who will render the HTML page you can do something like this:
#Controller
public class CustomChannelController {
private Setting setting;
private Diagram diagram;
private Channel channel;
#RequestMapping(value = "/customchannel", method = RequestMethod.GET)
public ModelAndView getId(Model uiModel) {
uiModel.add("options", this.setting);
return new ModelAndView("yourPage", uiModel) ;
}
Then in the HTML page you can use JSTL in this way:
<table>
<tr>
<td>
<label class="col-md-12 control-label"> <%=language['UI.reportSetting.channel']%> : </label>
</td>
<td>
<select id="selectReportChannel" class="form-control">
<c:forEach items="${options}" var="option">
<option value="${option.value}">${option.text}</option>
</c:forEach>
</select>
</td>
</tr>
</table>
Ok, I have found a solution. First a need to create a Spring MVC Controller then a Service and link then the Controller to the Backbone model file.
I have a JSP that has a form that looks like this:
<form method="GET" action="ManagerLogicServlet?action=salesreport" >
<select name="monthList">
<option value="1">January</option>
<option value="2">February</option>
<option value="3">March</option>
<option value="4">April</option>
<option value="5">May</option>
<option value="6">June</option>
<option value="7">July</option>
<option value="8">August</option>
<option value="9">September</option>
<option value="10">October</option>
<option value="11">November</option>
<option value="12">December</option>
</select>
<input type="submit" value="Submit">
</form>
I am trying to send over a query string with attribute action = salesreport which will be a condition that will return a sales report for the selected month (don't mind the missing default value). I submit the form over to the ManagerLogicServlet which has this code snippet:
..String action = request.getParameter("action");
if (action.equalsIgnoreCase("salesreport")){
forward = SALES_REPORT;
int month = Integer.parseInt(request.getParameter("monthList"));
String monthString = new DateFormatSymbols().getMonths()[month-1];
request.setAttribute("monthString", monthString);
request.setAttribute("salesReport", salesDAO.getSalesReport(month));
} else if..
But the action attribute is set to null. Why is this?
Because your form is using the GET method, the parameters from the action attribute are being discarded. If you insist on using GET, then you can include an <input> tag containing the parameter you wish to pass on to the servlet. Try doing this:
<form method="GET" action="ManagerLogicServlet?action=salesreport" >
<input type="hidden" name="action" value="salesreport">
<select name="monthList">
<option value="1">January</option>
...
</select>
<input type="submit" value="Submit">
</form>
The alternative would be for you to leave your code as is, but change the form's method to POST.
Its working fine.
I tried this
HTML
<form action="AnyServlet?action=salesreport" method="post">
<input type="submit" value="Submit Data" />
</form>
AnyServlet.java
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String action = request.getParameter("action");
System.out.println("action=="+action);
}
Output
action==salesreport
UPDATE
When i changed from "post" to "get",I am getting issue too.You can use hidden input field if you want go with "get".
I am trying to get values to a drop down list based on the previous value selected from another drop down list. I am able to call to java class from the servlet and the values are returned to servlet but it is not getting passed down to jsp page
jsp page part(index.jsp)
<select id="region" name="region" class="form-control" onchange="getgroups()" required="required" >
<option value="" default selected>Select region</option>
<option value="region1">region1</option>
<option value="region2">region2</option>
<option value="region3">region3</option>
<option value="region4">region4</option></select>
The onchange value in region calls this function
function getgroups(){
var j = document.getElementById("region");
var s = document.getElementById("secret_key");
var a = document.getElementById("access_key");
var output = $.ajax({
type: 'POST',
url: 'http://localhost:8066/VMMigratorNew/ec2util',
data: {"region":j.value,
"secret_key":s.value,
"access_key":a.value,
},
success: function(response) {
return output.responseText;
}
});
}
and in servlet
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String region = request.getParameter("region");
String secretKey = request.getParameter("secret_key");
String accessKey = request.getParameter("access_key");
List<String> vpcs = RunEc2Command.getVPCForUSer(AWS_ACCESS_KEY, AWS_SECRET_KEY, region);
if(vpcs != null && vpcs.size() > 0) {
request.setAttribute("vpclist", vpcs);
}
request.getRequestDispatcher("/index.jsp").forward(request, response);
}
}
and in the same index.jsp page , I am trying to show the list values in a drop down box which is in index.jsp itself.
<select id="vpc" name="vpc" class="form-control" placeholder="Choose VPC" >
<option value="" default selected>Select VPC</option>
<c:forEach items="${vpclist}" var="vpcs">
<option>
${vpcs}
</option>
</c:forEach>
</select>
I need to get the value of VPC in drop dron box after selecting the value from region drop down box. Thanks for the help in advance.
Currently, the workflow in your servlet is suitable for a synchronous request, which requires the servlet to return the whole HTML in the HTTP response for the browser to render. However, it seems to me that your intent is instead of querying the servlet in order to obtain a VPC list, and you are trying to pose the query asynchronously using AJAX.
Hence, my suggestion would be to let the servlet return the VPC list in some format (e.g., JSON). In the success callback, you should modify the DOM in order to insert the list you received.
I am using the following JQuery, JSP and Controller to return list of cities upon changing the country drop down menu on my app JSP page, yet I think the dataType, success parameters in the JQuery are not correct as I am not getting back the list. So can someone please tell me what I am doing wrong here and how I can get the list of Cities to add them to the cities drop down menu upon changing the Country drop down menu?
Thanks for your time
<script type="text/javascript">
function loadCity(){
var countryData="countryId="+$(country).val();
$.ajax({
type: "POST",
url: "LoadCities.htm",
data:countryData,
dataType: "javascript",
success: function(cities){
loadCities(eval(cities))
}
});
}
function loadCities(citiesLst){
clearCitiesDD();
for(var i=0;i<citiesLst.length;i++){
var city=citiesLst[i];
appendCity(city.id,city.value);
}
}
function clearCitiesDD(){
$('#cityDD').find('option').remove();
}
function appendCity(id,cityName){
$('#cityDD').append($("<option id='"+id+"'>" + cityName + "</option>"));
}
}
</script>
and in my application controller I have the following code:
#RequestMapping(value = "/LoadCities.htm", method = RequestMethod.GET)
public #ResponseBody
List<City> getCityByCountryID(HttpServletRequest request, HttpServletResponse response)
throws Exception {
List<City> list=
icitys.getCitiesByCountry(Long.parseLong(request.getParameter("countryID")));
return list;
}
and in the JSP file I have the following City and country drop down menus:
<tr>
<td align="right">Country</td>
<td align="left">
<select id ="country" name="country" onchange="loadCity()">
<option value="0">--select--</option>
<c:forEach var="countrylst" items="${countriesList}">
<option value="${countrylst.id}">${countrylst.countryName}</option>
</c:forEach>
</select>
</td>
</tr>
<tr>
<td align="right">City</td>
<td align="left">
<select id="cityDD" name="cityDD">
<option value="0">--select--</option>
</select>
</td>
</tr>
Hope you got solution after changing $(country) to $('#country').
One more thing, you put dataType as "javascript" but avail data types are xml, json, script, or html.
Better try with html.
Good luck.
Should
var countryData="countryId="+$(country).val();
not be
var countryData="countryId="+$('#country').val();
Looking for a way to call Server side method (Java) upon dropdown selection-change and based on the server output (TRUE OR FALSE), enable or disable few checkboxes. Would highly appreciate if anyone can provide recommendations around the same.
I've coded a quick example to show you how this would be done. First you will need to set up your java app to allow ajax calls. The java app will need to take in as input a single post variable name selected which is the value of the selected option in the dropdown menu. The java app will then need to return a json string formatted similar too:
{
"disabled":[
"1",
"3",
"5"
]
}
The 1, 3, and 5 represent the ids of the checkboxes you would like to be disabled. These can be any ids of any of the checkboxes. If it isn't in this array, it will be set to enabled by default.
HTML:
<select id="choiceSelector">
<option value="1">Something 1</option>
<option value="2">Something 2</option>
</select>
<br/><br/>
<div id="changingCheckboxes">
<input type="checkbox" name="" id="1"><br/>
<input type="checkbox" name="" id="2"><br/>
<input type="checkbox" name="" id="3"><br/>
<input type="checkbox" name="" id="4"><br/>
<input type="checkbox" name="" id="5"><br/>
<input type="checkbox" name="" id="6">
</div>
Javascript/jquery
function UpdateCheckBoxStatus ()
{
var CurrentChoice = $('#choiceSelector').val();
$.ajax({
url: "####YOUR JAVA APP URL####",
data: { "selected": CurrentChoice },
type: "post",
dataType: "json",
success: function (data)
{
SetCheckbox($('#changingCheckboxes').children("input:[type='checkbox']"), true);
$.each(data.disabled, function ()
{
SetCheckbox($('#changingCheckboxes #' + this), false);
});
}
});
}
/// Sets the checkbox to enabled or disabled
/// #param th Jquery reference of one or more checkboxes
/// #param usable True/False if the checkbox is enabled/disabled
function SetCheckbox (th, usable)
{
if (usable)
th.removeAttr("disabled");
else if (!usable)
th.attr("disabled", true);
}
$(function ()
{
$('#choiceSelector').change(UpdateCheckBoxStatus);
UpdateCheckBoxStatus(); //run for page load
});
Also, here is the jsfiddle of it: http://jsfiddle.net/bpstw/1/
Hope that helps.
Sure. Add a .change() handler to the drop-down element, within the handler make a $.ajax() request passing the selected value to your Java (possibly jQuery's shortcut ajax methods $.get() or $.post() would be easier than $.ajax()), and within the Ajax success callback check the server's response and enable or disable the relevant checkboxes.
Another similar solution for Radio button including Server side code in Java.
Jquery/HTML
Value1
Value2
Value3
<span id="changingCheckboxes">
<label for="group1">One</label>
<input type="radio" name="group1" id="1" value="option1"/>
<label for="group1">Two</label>
<input type="radio" name="group1" id="2" value="option2"/>
<label for="group1">Three</label>
<input type="radio" name="group1" id="3" value="option3"/>
<label for="group1">Four</label>
<input type="radio" name="group1" id="4" value="option4"/>
</span>
Jquery
function UpdateCheckBoxStatus () {
var CurrentChoice = $("#dropDownId").val();
$.ajax({
url: "/serverSideUrl",
data: { "selectedDropDownId": CurrentChoice },
type: "post",
dataType: "json",
success: function (data) {
SetCheckbox($("#changingCheckboxes").children("input:[type='radio']"), true);
$.each(data.disabled, function () {
SetCheckbox($("#changingCheckboxes #" + this), false); });
}
});
}
function SetCheckbox (th, state) {
if (state) th.removeAttr("disabled");
else if (!state) th.attr("disabled", true);
}
$('#dropDownId').change(UpdateCheckBoxStatus);
Java
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,
IOException {
String selectedValue = request.getParameter("dropDownId");
YourDao yourDao = new YourDao();
Map<String, List<String>> disabledOptions = cycleDao.determineStateDropDown(selectedTool);
String json = new Gson().toJson(disabledOptions);
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(json);
}