How to create a form with dynamic parameters using javascript? - java

I am trying to create a form using java script, the form is created but the dynamic param values to the form are not replaced. The following is my form....
var formVar='<form:form name="service_form" commandName="command1" action="/serviceProcess" method="post">';
formVar+='<label for="'+ paramsdata[2] + '">'+paramsdata[3]+'</label><br/>';
formVar+='<form:input type='+paramsdata[2]+' path="webParamMap['+paramsdata[2]+'].webValue" value='+ paramsdata[5] +' class="input"></form:input><br>' ;
formVar+='<label for=" '+paramsdata[2]+' ">'+paramsdata[3]+'</label><br/>';
formVar+='<div id="select">';
formVar+='<form:select path="webParamMap[' +paramsdata[2] + '].webValue">';
formVar+='<form:option value='+paramdata[8]+'>'+paramdata[9]+'</form:option>';
formVar+='</form:select></div>';
formVar+='</form:form>';
In the above form the label tag values(dynamic param values) are updated but the form:input and select tag values(dynamic param values) are not updated in the output.
please help me how to create these tags with dynamic parameters ?

JAVA != JAVASCRIPT
Notice:
<form:form>
This is server-side Java.
Your Javascript is client-side only.

With following script each element is getting its right value. I wonder why are you using "
<script>
var paramsdata = new Array();;
paramsdata[2]='param2';
paramsdata[3]='param3';
paramsdata[5]='param5';
paramsdata[8]='param8';
paramsdata[9]='param9';
var formVar='<form:form name="service_form" commandName="command1" action="/serviceProcess" method="post">';
formVar+='<label for="'+ paramsdata[2] + '">'+paramsdata[3]+'</label><br/>';
formVar+='<form:input type='+paramsdata[2]+' path="webParamMap['+paramsdata[2]+'].webValue" value='+ paramsdata[5] +' class="input"></form:input><br>' ;
formVar+='<label for=" '+paramsdata[2]+' ">'+paramsdata[3]+'</label><br/>';
formVar+='<div id="select">';
formVar+='<form:select path="webParamMap[' +paramsdata[2] + '].webValue">';
formVar+='<form:option value='+paramsdata[8]+'>'+paramsdata[9]+'</form:option>';
formVar+='</form:select></div>';
formVar+='</form:form>';
document.body.innerHTML = formVar;
</script>

<script>
//helper function to create the form
function getNewSubmitForm(){
var submitForm = document.createElement("FORM");
document.body.appendChild(submitForm);
submitForm.method = "POST";
return submitForm;
}
//helper function to add elements to the form
function createNewFormElement(inputForm, elementName, elementValue){
var newElement = document.createElement("<input name='"+elementName+"' type='hidden'>");
inputForm.appendChild(newElement);
newElement.value = elementValue;
return newElement;
}
//function that creates the form, adds some elements
//and then submits it
function createFormAndSubmit(){
var submitForm = getNewSubmitForm();
createNewFormElement(submitForm, "field1", "somevalue");
createNewFormElement(submitForm, "field2", "somevalue");
submitForm.action= "someURL";
submitForm.submit();
}
</script>
<input type="button" value="Click to create form and submit" onclick="createFormAndSubmit()">

Related

How to get the list in controller through jQuery

I have a jsp page , from which I am getting the list of the checkboxes selected by a user.
And as per the selected checkboxes I want to call my controller using the jQuery.
<input type="checkbox" name="XYZ" value="hello1"/>Hello1<br>
<input type="checkbox" name="XYZ" value="hello2"/>Hello2<br>
I obtained all the values in the jQuery and set all the parameters into a variable as given below.
var allVals = [];
$("input[name=XYZ]:checked").each(function() {
allVals.push($(this).val());
});
and I am using an AUI to call my controller, I am passing the value as parameter.
AUI().use('aui-base',
'aui-io-request',
'liferay-portlet-url',
function(A) {
var A = AUI();
var myResourceURL = Liferay.PortletURL.createResourceURL();
myResourceURL.setResourceId('getABC');
myResourceURL.setParameter("action",'ZYX');
myResourceURL.setPortletId(pid);
myResourceURL.setParameter("list",allVals);
A.io.request(myResourceURL.toString(),
{
method : 'post',
dataType : 'text',
on : {
start : function() {
.
.
.});
And in my controller I want to obtain the list and my controller is like this:
System.out.println(request.getParamter("list"));
This statement is just giving me the first selected element, not the complete list of the elements.
Is there something I am missing , or any other way to do it??
I think you will need to go with 'getParameterNames()' instead http://docs.oracle.com/javaee/6/api/javax/servlet/ServletRequest.html#getParameterNames()
Hope it helps

How to send data from struts2 to a javascript function to draw a chart

I need to add a dynamic chart into a webapp of mine.
I have choosen chartjs as library (for the line charts)
After the creation of the page with the chart inside and the definition of the action that retrieves data from database I am experiencing some problems sending data from the action to the script that generates the line chart.
The servlet gives as output an ArrayList of Beans
#Action(value="/graphDataFetcher")
public String execute(){
//Connessione a database
DBUtility database= new DBUtility();
Connection connessione=database.getConnected();
listamusei=database.getMusei(connessione);
//Recupero in liste di musei e mostre correlate
for(Museo ms: listamusei){
mostre=new ArrayList<Mostra>();
mostre=database.getMostraInMuseo(String.valueOf(ms.getId()), connessione);
ms.setMostre(mostre);
}
//Disconnessione da database
database.getDisconnected();
return "ok";
}
This is the scripts that "rules" the chart, I want to set the bean's attributes as value1, value2 , value3.. and so on.
<script>
var randomScalingFactor = function(){ return Math.round(Math.random()*100)};
var lineChartData = {
labels : ["January","February","March","April","May","June","July"],
datasets : [
{
label: "My First dataset",
fillColor : "rgba(220,220,220,0.2)",
strokeColor : "rgba(220,220,220,1)",
pointColor : "rgba(220,220,220,1)",
pointStrokeColor : "#fff",
pointHighlightFill : "#fff",
pointHighlightStroke : "rgba(220,220,220,1)",
data : [value1, value2, value3, value4]
},
]
}
window.onload = function(){
var ctx = document.getElementById("canvas").getContext("2d");
window.myLine = new Chart(ctx).Line(lineChartData, {
responsive: true
});
}
</script>
Does someone have some idea about how to fix this?
you can use by two ways
1. take a list in action with setter, getter and add data in this list. In jsp page use strcts tag library and in javascript variable put list data. Then call chartjs library function with data like
<script type="text/javascript">
var a = new Array();
<s:iterator var="newsVar" value="newsList" status="newsStatus">
a[<s:property value="#newsStatus.index"/>]='<s:property value="id"/>';
</s:iterator>
$(document).ready(function(){
chartjsfunction(a);
});
</script>
send ajax call for data to action and send data to chartjs library function.

populate hidden input form fields based on URLparameters

I have a ppc landing page that I want to change the hidden value of a form field based on the URL parameter.
The field
<input id="Campaign_ID" name="Campaign_ID" type="hidden" value="7g012455dv5441vdf">
The URL would be something like mysite.com/?campaignidvalue=7g012455dv5441vdf
There will be other field "values" that are also based on the URL parameter, so it has to tie the "input id" (or name) to that specific value.
EDIT: There was an error in my code.
PHP would be the easiest!
<?php
if(!empty($_GET['campaignidvalue']))
{
echo '<input id="Campaign_ID" name="Campaign_ID" type="hidden" value="'. $_GET['campaignidvalue'].'"/>';
}
?>
This block will check to see if the value is passed in a GET parameter, and then echo it out into a hidden form field.
The first part:
if(!empty($_GET['campaignidvalue']))
Is checking to see if a parameter named Campaign_ID is being passed.
So your URL of:
mysite.com/?campaignidvalue=7g012455dv5441vdf
Would allow the code to continue, as it is not empty.
This section is the part that actually displays it on the page.
echo '<input id="Campaign_ID" name="Campaign_ID" type="hidden" value="'. $_GET['campaignidvalue'].'"/>';
If you view the source of the HTML page, you would see
By using this function:
function getParameterByName(name) {
name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regexS = "[\\?&]" + name + "=([^&#]*)";
var regex = new RegExp(regexS);
var results = regex.exec(window.location.search);
if(results == null) {
return "";
} else {
return decodeURIComponent(results[1]);
}
}
You'll be able to get any URL parameter by name, like so:
var cid = getParameterByName(campaignidvalue);
Then, once you have the value you can use jQuery to set it, like so:
$(function() {
$("#Campaign_ID").val(cid);
});

Generate link with two input fields

I have Two Input Fields
Field1 and Field2
I want to generate a external link when clicking submit button
e.g. of the link as follow,
www.mystie.com/field1 + sometext + field2
I need this formula to use with Google map direction
user request.getParameter( "field1" ) in your action servlet
String link = request.getParameter( "field1" ) +"sometext" + request.getParameter( "field2" );
where your html is
<form action="myServlet" method="post">
<input name="field1"/>
<input name="field2"/>
</form>
String link = String.format("www.mysite.com/%s/sometext/%s",field1.getText(),field2.getText());
You can use Javascript to do so.
Try this
function submitclick(){
var text1= document.getElementByID("feild1").value;
var text2= document.getElementByID("feild2").value;
document.getElementByID("submitbuttonATag").href=text1+sometext+text2;
// Finally when the link is modified generate click
document.getElementByID("yourA_tag").click();
}
Using jquery
("#submitButton").click(function(){
var url="www.mysite.com/";
url= url + $("#feild1").val();
url = url + "sometext";
url = url + $("#feild2").val();
//Then use your url
});

Passing selected check boxes using jQuery servlet [duplicate]

This question already has answers here:
How to send request parameter array to servlet using jQuery $.ajax?
(4 answers)
Closed 6 years ago.
How can I pass selected checkbox values to another servlet (not below one) using jQuery post method?
This is my servlet code for generationg check boxes on the html page I am using json
for(int i=0;i<roles.size();i++){
JSONObject msg = new JSONObject();
msg.put("selector", "#roles");
//<input type=radio name="radio" value="<%=bean.getSno()%>"></td>
msg.put("msg",
"<input type=checkbox id="+'"'+"checkedroles"+'"'+"name="+'"'+"checkedroles"+'"'
+"value="+roles.get(i)+">"+roles.get(i)+"<br>");
messages.put(msg);
}
this is the jquercode
*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
$(document).ready(function(){
//global vars
var UserName = $("#UserName"); //user name field
var FirstName = $("#FirstName"); //first name
var LastName=$("#LastName");
var StreetAdress=$("#StreetAdress");
var City=$("#City");
var Province=$("#Province");
var Organization=$("#Organization");
var email=$("#email");
var phone=$("phone");
var checkedroles=$("#checkedroles");
var selected = new Array();
function checkCommentsForm(){
return true;
}
$("input:checkbox[name=checkedroles]:checked").each(function() {
selected.push($(this).val());
});
//When form submitted
$("#Reg").submit(function(){
if(checkCommentsForm()){
$.ajax({
type: "post",
url: "loginProcess.jsp",
data: {user : UserName.val(), fname : FirstName.val(),lname : LastName.val()
,stAddress:StreetAdress.val(),city:City.val(),prov:Province.val(),org:Organization.val()
,mail:email.val(),ph:phone.val(),'ch[]':selected},
success: function(data) {
}
});
}
});
});
also pls tell me how to retrieve the array in the servlet
You haven't shown your HTML but from the looks of it, it seems like these values are in a form.
You could then use ('#Reg').serialize() instead. This will Encode a set of form elements as a string for submission. - it will include all successful controls so all checked checkboxes will be included automatically as will all enabled text fields.
$("#Reg").submit(function(){
if(checkCommentsForm()){
$.ajax({
type: "post",
url: "loginProcess.jsp",
data: $(this).serialize(),
success: function(data) {
}
});
}
});
To retrieve the submitted values in your servlet, use the ServletRequest#getParameter() and ServletRequest#getParameterValues() methods. The former for when you have just one value for a parameter (for example, a test field) and the latter when you can have multiple values with that parameter name, for example, multiple checkboxes with the same name as is the case in your question. So you'd write something like this in your servlet:
String [] checked = request.getParameterValues("checkboxname");

Categories