I have done this ajax code to send data from jsp to servlet.
My ajax code in jsp is as follows:
$(document).ready(function(){
$("#process").click(function(){
console.log($("#processlist").val());
$.ajax({
url: "processtimesheet.do",
type : 'POST',
data : {processlist : $("#processlist").val()},
success : function(response){
alert(response);
window.location.reload(true);
}
})
});
});
The value in JSP is getting picked from the below EL.
<input type="hidden" name="processlist" id="processlist" value="${timesheetList}">
I am getting the values in the servlet..
[com.manager.model.Timesheet#a2a87e, com.manager.model.Timesheet#e3eda6, com.manager.model.Timesheet#74c85, com.manager.model.Timesheet#130bc16]
How do I convert these values back into List ?
If you right click and inspect near that hidden input element, you can see that input, in fact, has the value like com.manager.model.Timesheet#a2a87e, com.manager.model.Timesheet#e3eda6, com.manager.model.Timesheet#74c85, com.manager.model.Timesheet#130bc16 . The data is unusable.
This means you embedded full object to the input field. You can instead use/embed any unique field of Timesheet type and return that list to servlet. Then you can identify which list is selected at server side.
Assuming you have id field in Timesheet class, construct an id list:
<input type="hidden" name="processlist" id="processlist" value="${timesheetIdList}">
And servlet:
Map<Integer, Timesheet> index = ...;// map (unique index) construction
List<Timesheet> listSelected = new ArrayList<>;
for(int i = 0; i<idarray.length; i++) {
if(index.containsKey(idarray[i])) {
listSelected.add(index.get(idarray[i]))
}
}
Related
I'm using the next Spring form tag on my project:
<form:select path="eps.eps_id_eps" id="entidad" style="width: 400px;">
<form:options items="${EPSs}" />
</form:select>
I need to change the "items" values so i can display another data to a same select form tag, i.e. dynamically 'items="${EPSs}"' changes to 'items="${foo}"'
IS THERE Any mode to change items value in js/jquery or by ModelAttribute tag in server side?
Step 1 : Define a controller to receive foo list
#RestController
public class FooController{
#GetMapping("/foo")
public List<String> getFooItems(#RequestParam String eps){
return Arrays.asList("foo1","foo2");
}
}
Step 2 : Define a jquery to listen on eps select changes
$(document).ready(function(){
$("#entidad").change(function(){
var eps = $(this).val();
$.ajax({
url: '/foo?eps='+eps,
type: 'GET',
success:function(response){
var len = response.length;
//clear previous selection, eps_select is the select you want to complete
$("#eps_select").empty();
for( var i = 0; i<len; i++){
var foo = response[i];
$("#eps_select").append("<option value='"+foo+"'>"+foo+"</option>");
}
}
});
});
});
I am passing HashMap using jQuery and JSON to JSP page. The values being returned to jQuery success function are as follows:
Formatted JSON Data
{
"tableBird1":[
"001",
"Eurasian Collared-Dove"
],
"tableBird2":[
"002",
"Bald Eagle"
],
"tableBird3":[
"003",
"Cooper's Hawk"
]
}
I want to to populate a dropdown list based on these values where a dropdown contains two values.
Here is the code I am trying:
$.ajax({
type:"GET",
url: "url?",
data: { groupName: $('#groupNamesDD').val() }, // Data being passed through json from other drop down list
dataType: "json",
success: function(response){
$.each(JSON.stringify(response), function(key,value) { // I get this exception here - Cannot use 'in' operator to search for '294' in
var element = document.createElement("option");
for(var i = 0; i < key.length; i++) {
element.value= JSON.stringify(key);
element.data-value = JSON.stringify(key.value); // here I get run time exception - invalid left hand assignment
element.text=JSON.stringify(key.value);
document.getElementById("displayColumnsDropDown").add(element);
}
});
}
});
I want the output something like this:
<select id="displayColumnsDropDown" >
<option value="">-- Select --</option>
<option value="tableBird1" data-value="001" >001</option>
<option value="tableBird1" data-value="Eurasian Collared-Dove" >Eurasian Collared-Dove</option>
<option value="tableBird2" data-value="002" >002</option>
<option value="tableBird2" data-value="Bald Eagle" >Bald Eagle</option>
<option value="tableBird3" data-value="003" >003</option>
<option value="tableBird3" data-value="Cooper's Hawk" >Cooper's Hawk</option>
</select>
I got the possible solution form this link Can an Option in a Select tag carry multiple values?
I don't know how to create more than one values for drop down list dynamically other than this way. Is there any other possible solution?
EDIT 1:
Tried the following code:
$('#displayColumnsDropDown').append($('<option>', { value: key }).data-value(key.value).text(key.value));
In the second for loop of success method. I still get the same exception:
Cannot use 'in' operator to search for '805' in
I am answering my own question . It might help someone
var $select = $('#displayColumnsDropDown');
$.each(response,function(key,value)
{
if(value instanceof Array)
{
for(var i=0;i<value.length;i++)
{
$select.append('<option value=' + key + ' data-value= ' +value[i]+ '>' + value[i] + '</option>');
}
}
});
Syntax of my HashMap what I am passing to through JSON is something like this:
Map<String, List<String>> listOfColumns =new HashMap<String, List<String>>();
List is treated as Javascript Array which is taken as value in my jQuery loop.
Also I need not parse value ( which is response variable in my case )returned in success function because it is already being parsed for me.
The reason for my exception was I was parsing it again.
Thanks to all the previous answers on Stack Overflow.
Following is my jsp code.
<c:forEach items="${nameList}" var="studentList">
<tr>
<td style="padding-bottom: .5em;">
<a id="student" href="number?regNo=<c:out value="${studentList.regNo}"/>">
<span class="eachStudent">
<span class="studentName"><c:out value="${studentList.name}"/></span><br/>
<span class="collName"><c:out value="${studentList.collName}"/></span><br/>
<span class="deptName"><c:out value="${studentList.deptName}"/></span><br/>
</span>
</a>
</td>
</tr>
</c:forEach>
The above c:forEach lists
Name CollName DeptName
ABCD coll1 dept1
kfkdb coll1 dept2
jbdd coll2 dept3
Following is the code that lists the collName and deptName respectively.
<div>
Filter students by College (not required):
<select id="byCollege" name="byCollege" >
<c:forEach items="${uniqueCollList}" var="uniqueCollList">
<option value="${uniqueCollList}"/>
${uniqueCollList}</option >
</c:forEach >
</select >
</div>
<div>
Filter students by Department Name (not required):
<select id="byDept" name="byDept" >
<c:forEach items="${uniqueDeptList}" var="uniqueDeptList">
<option value="${uniqueDeptList}"/>
${uniqueDeptList}</option >
</c:forEach >
</select >
</div>
Now when I select a value from first dropdown, I want to filter the results given by foreach using the value selected in dropdown. I would like to do this in front end itself, rather going to the back end. May I know how can I do this?
After filtering the c:foreach result using value of first dropdown, if I select a value in second dropdown, I want the updated result of c:foreach to be filtered using the value selected in second drop down.
How can I do this?
If I want to do this in back end, what should I do?
PS:Following is the controller code that sends the list first time
#RequestMapping(value = "/name", method = RequestMethod.POST, params = { "studentName" })
public String searchStudentByCollOrDept(#RequestParam(value = "studentName", required = true)String studentName, ModelMap model){
List<OneStudentResult> nameList = resultService.getStudentList(studentName);
//TODO, null value check.
if(nameList.size() == 0 || nameList == null){
return "header";
}
if(nameList.size() != 0){
// Iterate the list that we get and add only one time a collName and deptname.So a Treeset.
Set<String> uniqueCollList = new TreeSet<String>();
Iterator<OneStudentResult> itr = nameList.iterator();
while(itr.hasNext()){
String collName = itr.next().getCollName();
if(!uniqueCollList.contains(collName)){
uniqueCollList.add(collName);
}
}
uniqueCollList.add(" Select a College ");
model.addAttribute("uniqueCollList", uniqueCollList);
Set<String> uniqueDeptList = new TreeSet<String>();
Iterator<OneStudentResult> itrDeptList = nameList.iterator();
while(itrDeptList.hasNext()){
String deptName = itrDeptList.next().getDeptName();
if(!uniqueDeptList.contains(deptName)){
uniqueDeptList.add(deptName);
}
}
uniqueDeptList.add(" Select a Department ");
model.addAttribute("uniqueDeptList", uniqueDeptList);
}
model.addAttribute("nameList", nameList);
return "nameResult";
}
I'm afraid there is no simple solution to your problem. You should consider doing this server-side with ajax updates. Client side filtering would either require you to parse the data from the HTML generated by your studentList or it would require you to inject the data as a JSON formatted array. In both cases you would end up with doubled data (server & client). Having the data on the client-side would only allow you to disable some of the option values, not hide them. So if you want real filtering in terms of not-showing some of the options then you should filter your lists on the server. To do so you should post the selected option from your first dropdown "byCollege" to your backend in order to retrieve a filtered "uniqueDeptList" that you use to rebuild the "byDept" checkbox. You might want to use jQuery for both tasks.
Steps:
1. Handle the change-event of the "byCollege" dropdown
2. Post the selected option value to your servlet
3. Filter the data in your servlet and return the filtered data as POST response (omitted in this example)
4. Remove the old select options and recreate them from the filtered data
$("#byCollege").change(function() {
$("select option:selected").first().each(function() {
// Get and convert the data for sending
// Example: This variable contains the selected option-text
var outdata = $(this).text();
// Send the data as an ajax POST request
$.ajax({
url: "yourjsonservlet",
type: 'POST',
dataType: 'json',
data: JSON.stringify(outdata),
contentType: 'application/json',
mimeType: 'application/json',
success: function(data) {
// Remove old select options from the DOM
$('#byCollege')
.find('option')
.remove()
.end();
// Parse data and append new select options
//(omitted here; e.g. $('#byCollege').append($("<option>").attr(...))
},
error: function(data, status, er) {
alert("error: " + data + " status: " + status + " er:" + er);
}
});
});
});
I am able to have the response from a servlet and also able to show it on jsp page, but if I try to populate the same in a drop down, i am not able to-
Servlet code
String sql = "SELECT records from department";
ResultSet rs = s.executeQuery(sql);
Map<String, String> options = new LinkedHashMap<String, String>();
while (rs.next()) {
options.put(rs.getString("records"),rs.getString("records"));
}
String json = new Gson().toJson(options);
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(json);
JSP code---
JS code
<script type="text/javascript">
$(document).ready(function () { // When the HTML DOM is ready loading, then execute the following function...
$('.btn-click').click(function () { // Locate HTML DOM element with ID "somebutton" and assign the following function to its "click" event...
$.get('/testservlet', function (responseJson) { // Execute Ajax GET request on URL of "someservlet" and execute the following function with Ajax response JSON...
//alert(responseJson);
var $select = $('#maindiv'); // Locate HTML DOM element with ID "someselect".
$select.find('option').remove(); // Find all child elements with tag name "option" and remove them (just to prevent duplicate options when button is pressed again).
$.each(responseJson, function (key, value) { // Iterate over the JSON object.
$('<option>').val(key).text(value).appendTo($select); // Create HTML <option> element, set its value with currently iterated key and its text content with currently iterated item and finally append it to the <select>.
});
});
});
});
</script>
HTML Code--
<input type="button" class="btn-click" id="best" value="check"/>
<div id="maindiv" style="display: block"></div>
If I create a <ul> and <li> I can have the data from the response on my page but not able to create the select options? Any help on this would be great.
Try it again after removing beginning /.
$.get('testservlet', function (responseJson)
The JSON string is not in proper way. It should be something like this. Why are you using JSON string here whereas you are passing only records as key as well as value.
Simply return a comma separated string from Servlet and split it jQuery.
Find example here for Iterating a comma separated string
Sample code:
var items = responseJson.split(',');
for ( var i = 0; i < items.length; i++) {
$('<option>').val(items[i]).text(items[i]).appendTo($select);
}
Actually i've two comboboxes.First one contains the countries list,and second one contains the states list.. if i click the particular country,the 2nd combobox should only show the states related to selected particular country only.
how to do this in Struts2 jsp form,thanks in advance.....
you can do this of status with javascript :
if( document.getElementById("combo..1").value =="1thvalue" ) {
document.getElementById("combo..2").value =="2thvalue"
}
Assuming you have jQuery, try this:
<select id="country">
<option>1</option>
<option>2</option>
<option>3</option>
</select>
<select id="state"></select>
var data = ["state1", "state2", "state3"];
$("#country").change(function(){
// get data with $.ajax ..
var option;
$.each(data, function(index, value){
option += "<option>" + value + "</option>";
});
$("#state").empty().append(option);
});
You can try it out here: http://jsfiddle.net/jaiwo99/fgt5R/
html code
<select id="country">
<option>India</option>
<option>Pak</option>
<option>UK</option>
</select>
<select id="state"></select>
Jquery
var data = [
{"India":"tamilnadu"}
,{"Pak": "lokur"},{"UK" :"london"}
]; // Json data
$("#country").change(function(){
var option;
$.each(data, function(index, value){
$.each(value,function(countr,stat){
var x=$("#country").val();
if(x==countr){
$("#state").empty();
$("#state").append("<option>"+stat+"</option>");
}
});
});
});