There is a JSP page in which i have an ArrayList variable. I need these arraylist values(txt1 and txt2) in script tag.I have tried lots of combinations and googling but didnot succeed.
javascript function
function fun1()
{
// how to get arraylist values
}
JSP page:
<body>
<%
ArrayList<String> al= new ArrayList<String>();
al.add("txt1");
al.add("txt2");
out.println("<input type=text id=" + al.get(0) + ">");out.println("<br>");
out.println("<input type=text id= " + al.get(1) + ">");out.println("<br>");
out.println("<input type=button id=btn1 value=click onClick=fun1(); > ");
%>
</body>
Thanks for reply
Inside javascript you can use Scriplets very well
Assume the list 'arrayList' is having [1,2,3,4] in java (JSP)
you can get the array list by this
function fun1()
{
var list = '<%= arrayList %>';
}
if you print the variable list, it will be a string with value '[1,2,3,4]'
You can then split this using Regex or simple string operation
<body>
<%
ArrayList<String> al= new ArrayList<String>();
al.add("txt1");
al.add("txt2");
out.println("<input type=text id=" + al.get(0) + ">");out.println("<br>");
out.println("<input type=text id= " + al.get(1) + ">");out.println("<br>");
out.println("<input type=button id=btn1 value=click onClick=fun1(); > ");
%>
</body>
<script>
// try the script here
</script>
Try something like this.
<script>
var myArray=new Array();
myArray[0] = '<%= al.get(0) %>';
myArray[1] = '<%= al.get(1) %>';
<script>
You could create a script tag which creates an array in js that holds all you values. I'm not familar with jsp but deppending on oyur code it could look like:
out.println("<script type='text/javascript'>");
out.println("var myJsArray = new Array();");
foreach(var arrayMember in al)
{
out.println("myJsArray.push(" + arrayMember + ");");
}
out.println("</script>");
In Js just use the array:
function fun1()
{
var firstArrayMember = myJsArray[0];
// or whatever you want to do
}
You could also use assoziativ arrays if you have a key for a specific array member.
Hope you got the idea
I would have the Java code somewhere else, but if you insist on having it inside your JSP, try having readable HTML and only output Java content using <%=...%> - something like this:
<%
ArrayList<String> list = new ArrayList<String>();
list.add("text1");
list.add("text2");
%>
<body>
<form ...>
<input type="text" id="<%=list.get(0)%>" />
<input type="text" id="<%=list.get(1)%>" />
<input type="button" id="button1" value="Click" onclick="functionOne();" />
</form>
<script type="text/javascript">
function functionOne() {
alert(document.getElementById("<%=list.get(0)%>").value);
}
</script>
</body>
Related
I have dropdown with options and the values. I can get the option value by the dropdown name in servlet but how can i get the dropdown "value" in servlet. In screenshot, temporarily i concatenated the with options but i want to store value in variable in servlet.
Please help:
HTML:
<input type="text" name="taxiDropdown" id= "taxiDropdown" placeholder="Search taxi...">
</div>
<div class="scrolling menu">
<%
List eList = (ArrayList) session.getAttribute("taxiInfo");
%>
<%
for (int i = 0; i < eList.size(); i++) {
%>
<div class="item" data-value="<%=((TaxiInfo) eList.get(i)).getID()%>">
<div class="ui green empty circular label"></div>
<%=((TaxiInfo) eList.get(i)).getTaxiPlate() +" "+ ((TaxiInfo) eList.get(i)).getID() %>
</div>
<%
}
%>
</div>
</div>
Servlet:
String val = request.getParameter("taxiDropdown");
(in "val", I want to store the value of the dropdown not the option text)
In JSP you should have something like that:
<form method="post">
<select name="taxiDropdown" id="taxiDropdown">
<%
List<TaxiInfo> eList = (List<TaxiInfo>) request.getAttribute("taxiInfo");
for (TaxiInfo taxiInfo : eList) {
%>
<option name="<%=taxiInfo.getTaxiPlate()%>" value="<%=taxiInfo.getID()%>"><%=taxiInfo.getTaxiPlate()%></option>
<%
}
%>
</select>
<input type="submit" />
</form>
Then in controller/servlet you will receive the id of TaxiInfo:
String val = request.getParameter("taxiDropdown");
System.out.println(val);
Or in your case you should set a hidden input with javascript with desired value.
added this code in html:
Move value of the dropdown selection to hidden textbox
<script type='text/javascript'>
$(function() {
$('#driverdp').change(function() { <-- this is my dropdown -->
var x = $(this).val();
$('#driverid').val(x); <-- this is my textbox -->
});
});
</script>
Servlet:
get the value of hidden text in servlet
String text= request.getParameter("driverId");
hope it will help someone
I am developing a web application in which I which I have a JavaScript array and I want this array in my JSP page and iterate it save the data in database.
var value = response;
for (var key in value) {
if (value.hasOwnProperty(key)) {
alert(key + " -> " + value[key]);
var sample = new Array();
sample=value[key];
console.log(sample);
// document.getElementById('');
}
}
});
I want this data on my JSP page is it possible. If it is possible, then how?
You can have javascript in jsp but that will always execute on client side. So if you want to save some stuff on trigger of some event inside browser you can do that by making ajax call or form submission. Ajax is preferred way because its faster and better experience for user
But if you have intention of execution of javascript on server side thats not possible
Java script client side script whereas jsp is server side script so you can't simply do this.
What you can do is submit the calculated variable from javascript to server by form-submission, or using URL parameter or using AJAX calls and then you can make it available on server to store in database.
Client Side:
<script type="text/javascript">
var n = document.getElementById("data");
var f=new Array( "apple", "orange", "mango" );
n.value = f;
</script>
<form action="Your_JSP.jsp" method="POST">
<input type="hidden" id="data" name="data" value="" />
<input type="submit" />
</form>
Server Side:
<%
String val = request.getParameter("data");
String aa[]=val.split(",");
for(String x : aa )
out.println(x);
//now hereyou can use aa array tostore in database or do whatever you want
%>
Try this if you have two different jsp:
first.jsp
<script>
var response = [];
...
var put = function(form) {
form.resp.value = response.join(','); //using comma as separator
};
</script>
<form onsubmit='put(this)' method='next.jsp' method='post'>
<input type='hidden' name='resp' />
<button>Submit</button>
</form>
next.jsp
<%
String[] resp = request.getParameter("resp").split(",");
%>
Response is: ${param.resp} <!-- debugging -->
yes , its possible to do that. you can show array in HTML tag
<!DOCTYPE html>
<html>
<head>
<script>
var value=response;
for (var key in value) {
if (value.hasOwnProperty(key)) {
alert(key + " -> " + value[key]);
var sample = new Array();
sample=value[key];
console.log(sample);
// do here as
document.getElementById("array").innerHTML = sample;
// here array is <p> tag in html and sample is array which will be shown in jsp page.
}
}
</script>
</head>
<body>
<form action="get.jsp" method="POST">
<p id="array" name="array" type="hidden"></p>
<input type="submit" />
</body>
</html>
in get.jsp you will able to get value from array as:
<%
String []array = request.getParameter("array").split(",");
//this String array you can use to store data in DB
%>
I have a HTML page with dinamycally changing number of select elements.
<script>
function getValues() {
var selects = document.getElementsByTagName('select'),
arr = Array.prototype.slice.call(selects),
selectValues = arr.map(function (select) {
return select.value;
});
return selectValues;
}
</script>
<script type='text/javascript'>
function moreSelect() {
for (i = 0; i < number; i++) {
// Append a node with a random text
container.appendChild(document.createTextNode("Name " + (i+1) + ": "));
// Create an <input> element, set its type and name attributes
var input = document.createElement("select");
input.name = "name" + (i+1);
container.appendChild(input);
// Append a line break
container.appendChild(document.createElement("br"));
}
</script>
<form action="action"method="POST" onsubmit="return getValues;">
More selects (max. 9):<br>
<p>
<input type="number" id="name" name="name" value="0"
min="0" max="9"><br />
<button type="button" onclick="moreSelect()">Add</button>
<br>
<p>
<br>
<div id="container" /></div>
<p>
<br> <br> <input type="submit" value="Go">
</form>
I want to collect this values to a List or an Array before the POST method and give this parameter list to my Java controller like this:
#RequestParam("allValues") List<String> allValues
Edit: I edited it, but doesn't works.
Get all selects, transform them to a real Array by Array.prototype.slice. Now you can use map to get all values. getElementsByTagName returns a HTMLCollection, that does not support map(), etc.
var selects = document.getElementsByTagName('select'),
arr = Array.prototype.slice.call(selects),
selectValues = arr.map(function (select) {
return select.value;
});
Now selectValues is an Array of the select values.
You can add one hidden form parameter say with name "allValues" and using javascript before posting Form, you can add all select values in that parameter.
I'm trying to pass an ArrayList from handle.jsp to main.jsp, but it doesn't let me do it. It keeps saying "Type mismatch: cannot convert from Object to ArrayList".
main.jsp:
<%# page import="java.util.ArrayList" %>
<html>
<body>
<h1>Hobby Manager</h1>
<%
ArrayList<String> hobbies = session.getAttribute("hobbies");
out.println(hobbies.size());
out.println(session.getAttribute("hobbies"));
%>
<h2>Add new hobby!</h2>
<FORM action="handleAddHobby.jsp" method="get">
What new hobby are you wishing to add? <INPUT TYPE=text name=hobbyName /> <br/>
<INPUT TYPE=submit name=addHobby value="Add Hobby" />
</FORM>
</body>
</html>
handle.jsp:
<%# page import="java.util.ArrayList" %>
<html>
<body>
<%
ArrayList<String> hobbies = new ArrayList<String>();
String hobbyName = request.getParameter("hobbyName");
if(hobbyName == null){
out.println("Please enter a hobby before clicking add! Dummy.<br/>");
}
else{
hobbies.add(hobbyName);
for(int index = 0; index < hobbies.size(); index ++){
out.println(hobbies.get(index) + "<br/>");
}
session.setAttribute("hobbies", hobbies);
}
%>
</body>
</html>
I have tried passing it as a string object, and passing it as an object alone but nothing seems to work.
the problem is here ..
ArrayList<String> hobbies = session.getAttribute("hobbies");
Try typecasting it as getAttribute always returns Object.
ArrayList<String> hobbies = (ArrayList<String>)session.getAttribute("hobbies");
I have used setTimeout method to do this and passed a variable which contains time but my settimeout method takes only the initialized value of that variable and not the value that is fetched from database.
Here is my code:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Givetest</title>
<script type = "text/javascript">
function submitForm() {
document.forms[0].submit();
}
</script>
<script language="JavaScript" src="http://scripts.hashemian.com/js/countdown.js"></script>
</head>
<%
String ts=request.getParameter("testname");
session.setAttribute("tname", ts);
Connection con=null;
Statement s1=null;
Statement s=null;
ResultSet r1=null;
ResultSet r=null;
int t=120000;
String time=null;
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con=DriverManager.getConnection("jdbc:odbc:online_testing");
s=con.createStatement();
s1=con.createStatement();
r=s.executeQuery("select * from "+ts+"");
r1=s1.executeQuery("select duration from tests where testname="+ts+"");
if(r1.next())
{
time=r1.getString("duration");
t=Integer.parseInt(time)*60000;
logger.info(time);
}
else {
logger.info("No row found in db for test " + ts);
System.out.println("No row found in db for test " + ts);
out.println("<br>!! <b>No row found in db </b>for test " + ts + "<br><br><br>");
}
r1.close();
}
catch(Exception e1)
{
response.setContentType("text/html");
out.println(e1.toString());
}
%>
<body onload="setTimeout('submitForm()',<%=t%>)">
<div class="header"></div>
<div class="view" style="color: #050505">
<form action="Givetest" method="post">
<h1 align="center" style="color: #050505"><%=ts%></h1>
<%
int i=1;
while(r.next()){
String a = r.getString("question");
String b = r.getString("option1");
String c = r.getString("option2");
String d = r.getString("option3");
String e = r.getString("option4");
%>
Question <%=i%>:- <label> <%=a%></label><br>
<input type="radio" name="r<%=i%>" value="<%=b%>" checked><label><%=b%></label><br>
<input type="radio" name="r<%=i%>" value="<%=c%>"><label><%=c%></label><br>
<input type="radio" name="r<%=i%>" value="<%=d%>"><label><%=d%></label><br>
<input type="radio" name="r<%=i%>" value="<%=e%>"><label><%=e%></label><br>
<br>
<input type="hidden" name="h" value="<%=ts%>">
<%
i++;
}
r.close();
s.close();
con.close();
%>
<input type="submit" class="button">
</form>
</div>
<div class="copyright" align="center"> © SAUMYARAJ ZALA</div>
</body>
</html>
The mistake is in the where clause which should be like:-
r1=s1.executeQuery("select duration from tests where testname="+ts+"");
Moreover this code should be executed in servlets before it is passed to jsp
<body onload="setTimeout('submitForm()',<%=t%>)">
You are giving the value only once. DO you mean it gets value
int t=120000;
and not what is in data base? If so are you sure no error is being thrown?
By the way this is not the best way to write a web app - all in jsp - though it works, better is to make servlets and POJOs/ helper .java files for data base etc. Make sure your tomcat/ app server's temp folder are cleaned every time you restart - to make sure its taking latest jsp.
In jsp can have a text like 'Version 001' and increase that manually so your sure correct code version is running.
Use loggers or system.out.println if you do not have logger
r1=s1.executeQuery("select duration from tests where testname="+ts+"");
//if should be enough as you will only have 0 or 1 row per test?
if(r1.next())
{
time=r1.getString("duration");
t=Integer.parseInt(time)*60000;
} else{
logger.warn("No row found in db for test " + ts);
//okay for debug
out.println("<br>!! <b>No row found in db </b>for test " + ts + "<br><br><br>");
}
r1.close();
}
catch(Exception e1)
{
response.setContentType("text/html");
out.println("<br><br> <b> ERROR</b>" + e1.toString());
}
sql
testname="+ts+""
is very bad should use a prepared statement or you are asking for a SQL injection attack. look at owasp https://www.owasp.org/index.php/SQL_Injection_Prevention_Cheat_Sheet