How to pass dynamically added textbox to spring MVC controller java - java

$("#addButton").click(function () {
if(counter > 3){
alert("Only 3 textboxes allowed");
return false;
}
var selectfield = $('#selectcolumnlist option:selected').val();
var newTextBoxDiv = $(document.createElement('div')).attr("id", 'TextBoxDiv');
newTextBoxDiv.after().html('<input type="text" name="textbox_' + selectfield + '" class="form-control" id="textbox_'+selectfield+'" placeholder="' + selectfield + '" value="" style="width: 400px;"/><input type="button" value="Remove Field" class="remove_this" id="removeid" accessKey="'+selectfield+'"/>');
newTextBoxDiv.appendTo("#TextBoxesGroup");
$('#selectcolumnlist option:selected').remove();
counter++;
});
$("#TextBoxesGroup").on('click', '#removeid', (function() {
var a = $(this).attr('accessKey');
alert(a);
$(this).parent('div').remove();
$('#selectcolumnlist').append(new Option(a,a));
counter--;
}));
Above code is adding a textbox based on the dropdown select option. It can add a maximum of 3 textboxes.
How do I pass this textbox value to spring MVC controller.

It appears that you are using JQuery to build the UI. Assuming that you have a Spring MVC endpoint exposed at POST http://localhost:8080/api/boxes you can use jQuery.ajax() method:
$.ajax({
method: "POST",
url: "http://localhost:8080/api/boxes",
data: { textbox: "value" }
})
.done(function(msg) {
alert("Saved: " + msg);
});

Related

Display JSON data in table format with a submit button corresponding to each row

/* How do I Display json data into a table in a JSP Page with a submit button in each row. On clicking submit button, Row data should be sent to a servlet.
I have fetched json data from a Servlet using Ajax.
Below is my ajax call to get JSON data from Servlet */
function updateprofile(){
$.ajax({
url : 'abc/ConnectionInfo',
type: 'GET',
data: {},
data type: 'json'
}).done(function (data){
renderProfiles(data);
}).fail(function (){
toaster.error("Eror...");
});
}
function
renderProfiles(data){
//How can I implement this
method to display all the
data in table format with a
button corresponding to
each row. And on clicking
of the button it should
send a profile ID to
Servlet Post method.
}
You can use $.foreach loop to iterate your json data and show them in your table. Demo code(you need to do changes in below code as per your requirment) :
//your json data
var response = [{
"metric": "connected[qa_KCDz->Exre]"
},
{
"metric": "connected[qa_KTDz->Exre]"
},
{
"metric": "connected[qa_KPDz->Exre]"
}
];
var str = '<table border=1><tr>\n' +
'<th>Something</th>\n' +
'<th>Submit</th>\n' +
'</tr>';
//looping through json data
$.each(response, function(key, value) {
//get value
var s = value['metric'];
//getting index of [
var i = s.indexOf('[');
var data = s.slice(10, i + 8).trim();
str += '<td>' + value['metric'] + '</td>';
str += '<td> <form method="post" action="servletname"><input type="hidden" name="data" value=' + data + ' ><input type="submit" value ="send" ></form></td></tr>';
});
str += "</table>";
//appending data
$("#table").html(str);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="table"> </div>
Put above code of jquery under your function renderProfiles(data){..}.Also,under <form></form> tag i have added a hidden input field with the required value that you need to send to your servlet .Get that value using request.getParameter("data") in doPost method of servlet.

Change dynamically Item Value on <form:options> in Spring form select

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>");
}
}
});
});
});

how to make changes the value of one combobox when another changed in Struts2

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>");
}
});
});
});

AJAX call getting failed when I send duplicate parameter

I'm facing quite funny problem, the problem is--
In my application there is a functionality to add products into the shopping-cart, I've implemented this functionality using AJAX. When I add different items (e.g. Item-1, Item-2,..., Item-n) it works fine, but when I add same item again (e.g. Item-1, Item-1 OR Item-1, Item-2,..., Item-n, Item-1) it gets failed
following is my AJAX Code--
var xmlHttp;
//FUNCTION TO CREATE BROWSER COMPATIBLE OBJECT.
function createBrowserObject()
{
if (typeof XMLHttpRequest != "undefined") //Object for Netscape 5+, Firefox, Opera, Safari,and Internet Explorer 7
{
//alert("Obj created");
xmlHttp = new XMLHttpRequest();
}
else if (window.ActiveXObject) //Version for Internet Explorer 5 and 6.
{
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
if (xmlHttp == null) //Fails on older and nonstandard browsers
{
alert("Browser does not support XMLHTTP Request");
}
}
function addToCartChange()
{
if (xmlHttp.readyState == 4 || xmlHttp.readyState == "complete") //Check whether Server response came back with no errors.
{
document.getElementById("cart_div").innerHTML = xmlHttp.responseText;
}
}
function addToCart(titleId)
{
var lastIndex=cartID.substring(parseInt(cartID.lastIndexOf("_"))+1);
var titleId="product_title_"+lastIndex;
var priceId="product_price_"+lastIndex;
var productTitle=document.getElementById(titleId).innerHTML;
var productPrice=document.getElementById(priceId).innerHTML;
productPrice=productPrice.substring(parseInt(productPrice.lastIndexOf(";"))+1);
createBrowserObject();//CREATE BROWSER COMPATIBLE OBJECT.//
var url = "../AddToCartServlet"; // URL of server-side resource.//CALL TO THE SERVLET//
url += "?productTitle=" + productTitle + "&productPrice=" + productPrice;
xmlHttp.onreadystatechange =addToCartChange; //ASSIGN RESPONSE HANDLER FUNCTION NAME TO ONREADYSTATECHANGE//.
xmlHttp.open("GET", url, true); //INITIATE GET or POST REQUEST. (Here GET)
xmlHttp.send(null); // SEND DATA. (Always null in case of GET.)
}
My AddToCartServlet code is--
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
// TODO Auto-generated method stub
System.out.println("inside AddToCartServlet ");
String strProductTitle=request.getParameter("productTitle");// TO STORE THE VALUE IN productTitle VARIABLE.//
String strProductPrice=request.getParameter("productPrice");// TO STORE THE VALUE IN productPrice VARIABLE.//
AuthenticateServlet.strListItemName.add(strProductTitle);
AuthenticateServlet.strListItemPrice.add(strProductPrice);
String strBuffur="<table width='100%' border='0' cellspacing='0' cellpadding='0' class='cart_table'>";
float floatTotal=0;
for(int i=0; i < AuthenticateServlet.strListItemName.size(); i++)
{
System.out.println("inside loop strListItemName("+i+")= "+AuthenticateServlet.strListItemName.get(i));
strBuffur=strBuffur + "<tr id='item_"+i+"'>" + "<td width='58%' align='left' valign='middle'><strong><span class='prod_name'>"+AuthenticateServlet.strListItemName.get(i)+"</span></strong></td>"
+ "<td width='19%' align='center' valign='middle'>"
+ "<form id='form1' name='form1' method='post' action=''><label>"
+ "<input type='text' value='1' name='textfield' id='itemQty_"+i+"' class='cart_input' />"
+ "</label></form></td>"
+ "<td width='23%' align='left' valign='middle'><strong>Rs. "+AuthenticateServlet.strListItemPrice.get(i)+"</strong></td></tr>";
floatTotal=floatTotal+Float.parseFloat(AuthenticateServlet.strListItemPrice.get(i));
}
// System.out.println("Exit for.....");
strBuffur=strBuffur + "<tr class='total_td'>"
+ "<td colspan='2' align='right' valign='middle'><strong>Total:</strong></td>"
+ "<td align='left' valign='middle'><strong>Rs. "+floatTotal+"</strong></td></tr>"
+ "<tr> <td colspan='3' align='center' valign='middle'> <input name='' type='button' value='Check Out' class='add_cart' onclick='gotoCheckOut()'/></td></tr>"
+ "</table>";
response.getWriter().println(strBuffur);
}
In short, call to AddToCartServlet gets failed when I add Same item again. Please help.. Thanks..!
If the Collection You are using for adding item name ie AuthenticateServlet.strListItemName is a Set then this can be a reason for failure

POST data sent by Spring MVC is null on IE8

I have two text fields (pageField1) and pageField2) in Spring MVC where an user can input in page numbers. The javascript code retrieves the values in these textfields and sends as POST data to the controller. The code for retreiving the values and sending as POST data in javascript is exactly the same for both fields.
In the Controller, I use request.getParameter("value") to retrieve the POST data.
On Firefox and Chrome, values for both pageField1 and pageField2 are retrieved fine.
On IE8, request.getParameter("value") returns null for pageField1 but the correct value for pageField2.
This is really baffling, and I am stumped. I put an alert just before Spring MVC sends the POST data to the controller. The values are exactly the same for FireFox and IE, but when retrieved on the controller, its null on IE.
Any input would be great! I can post snippet of the code if needed.
Thanks!
Will try using HTTPtea. I already downloaded it, just have to configure it now.
Thanks!! Here is my JavaScript code:
Here is the JavaScript code:
functionPageField1(event){
if (event == null || event.keyCode == 13) {
var domain = document.getElementById('domainTextField').value;
var nameToFindExcl = document.getElementById('searchObjectsExclTextField').value;
var pageNumberExcl = document.getElementById('pageNumberExclTextField').value;
var pageCountExcl = document.getElementById('pageCountExclTextField').value;
var nameToFindIncl = document.getElementById('searchObjectsInclTextField').value;
var pageNumberIncl = document.getElementById('pageNumberInclTextField').value;
if (!isValidInput(pageNumberExcl,pageNumberIncl)){
return;
}
alert("/sysmgr/domains/viewDomainObjects.spr?domain=" + domain + "&nameToFindExcl=" + nameToFindExcl +
"&pageNumberExcl=" + pageNumberExcl + "&nameToFindIncl=" + nameToFindIncl + "&pageNumberIncl=" + pageNumberIncl);
/* Its the pageNumberExcl that is null in the controller, where as all other
values are fine.
In the above alert, I see the correct value for pageNumberExcl, but its null when I retreive it in the controller.
*/
window.location="/sysmgr/domains/viewDomainObjects.spr?domain=" + domain + "&nameToFindExcl=" + nameToFindExcl +
"&pageNumberExcl=" + pageNumberExcl + "&nameToFindIncl=" + nameToFindIncl + "&pageNumberIncl=" + pageNumberIncl;
}
}
//This is the snippet of the html code that defines the pageNumberExcl Field
<td>
<p align="right">
<fmt:message key="form.any.page"/> <input type="text" id="pageNumberExclTextField"
value="${pageNumberExcl}" size="3" onKeyPress="numberPageExcl(event)">
<fmt:message key="form.any.of"/> <input disabled type="text" style="border-style:none; background-color:white; color:black"
id="pageCountExclTextField" value="${pageCountExcl}" size="3">
</p>
</td>`

Categories

Resources