Can we initialize JavaScript variables with java in jsp page?
like,
<script type="text/javascript">
var refreshId = setInterval(function() {
var nv=<% out.print(num_voted); %>;
var tv=<%out.print(totalvoted); %>;
var m=<% out.print(month);%>;
var y=<% out.print(year);%>;
alert("refreshed");
$('#alertmessagebox').text("Total members voted "+nv+" out of "+tv+" for "+m+" " +y);
}, 9000);
$.ajaxSetup({ cache: false });
</script>
Code is not working as expected. :(
Is there way to do this? Why it is not possible by this way? shall we need to create header to do this?
Here is an example of setting Javascript variables in a JSP.
<head>
<%
String numVotedStr = request.getParameter("numvoted");
int numVoted = 0;
if (numVotedStr != null) {
numVoted = Integer.parseInt(numVotedStr);
}
%>
<script type="text/javascript">
function setInterval() {
alert("hello " + <%= numVoted %>);
}
</script>
</head>
<body>
<form>
<input type="button" onclick="setInterval()" value="Press Me"/>
</form>
</body>
</html>
To test, use the appropriate version of this URL:
http://localhost:8080/sandbox/example.jsp?numvoted=99
This will popup an alert box with the integral value of "numvoted" on the HTTP request, by producing an HTML page where the value is initialized in Javascript. (The code should have at least a try-catch for the parseInt() call, but this will serve as simple example.)
Related
I am working on a project where the client's requirement is to add a dynamic text box. I made the dynamic text box but I'm not getting the unique name of the text box.
Here is my code:
<script type="text/javascript">
function addfieldset() {
var namefieldset = document.getElementById("name").cloneNode(true);
document.getElementById("names").appendChild(namefieldset);
}
function deletefieldset(e) {
var namefieldset = e.parentNode;
namefieldset.parentNode.removeChild(namefieldset);
}
</script>
<body>
<%! public static int i = 1;%>
<% if (i > 0) { %>
<div id="names"><div id="name"><% out.print(i);%>Name: <input name="namefield<%= i%>" type="text"/>delete</div></div>
<input id="addnamebtn" type="button" value="Add Name" onclick="addfieldset()"/>
<% i++;
}%>
</body>
You are mixing two different codes. The key is to realize, where and when each code is executed - JSP on the server when the page is requested and rendered (i.e. before the response is sent to the browser) and Javascript in the browser, after the browser receives the already generated response.
I.e. you have to change the name of the new text field in the addfieldset() function (which means you have to have a counter, how many text fields there already is).
The java code in scriptlet is executed on the server side. Hence, cloning it again through Javascript will not execute the scriptlet again.
An another approach of what you are trying to achieve will be to store the count variable in javascript.
var count = 1;
function addfieldset() {
count++;
var namefieldset = document.getElementById("name").cloneNode(true);
var textField = namefieldset.getElementsByTagName('input')[0];
textField.setAttribute("name", "namefield" + count);
textField.value = "";
document.getElementById("names").appendChild(namefieldset);
}
function deletefieldset(e) {
var namefieldset = e.parentNode;
namefieldset.parentNode.removeChild(namefieldset);
}
<body>
<div id="names">
<div id="name">
<span>Name:</span>
<input name="namefield1" type="text" />
delete
</div>
</div>
<input id="addnamebtn" type="button" value="Add Name" onclick="addfieldset()" />
</body>
try this JavaScript and HTML
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<script type="text/javascript">
var i = 0;
function generateRow() {
i++;
var d = document.getElementById("div");
d.name = "food";
d.innerHTML += "<p>name"+i+" :<input type='text' name='name" + i + "' /> <a href='#' onclick='deletefieldset(this)'>delete</a></p>";
}
function deletefieldset(e) {
var namefieldset = e.parentNode;
namefieldset.parentNode.removeChild(namefieldset);
}
function onLoad() {
generateRow();
}
window.onload = onLoad;
</script>
<body>
<div id="div"></div>
<p>
<input type="button" id="addnamebtn" value="Add Name" onclick="generateRow()" />
</p>
</body>
</html>
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 want to execute the java script function of a child window on parent window, Even after changing the URL in the parent window.
I tried like below:
**Parent.html:**
<html>
<head>
<title>Parent window document</title>
</head>
<body>
<script type="text/Javascript">
function openChildWindow()
{
var s_url = "child.html";
var s_name = "ChildWindowDocument";
var s_specs = "resizable=yes,scrollbars=yes,toolbar=0,status=0";
var childWnd = window.open(s_url, s_name, s_specs);
var div = childWnd.document.getElementById("child_wnd_doc_div_id");
div.innerHTML = "Hello from parent wnd dddsfds";
}
</script>
<input type="button" value="Open child window document" name="sss" onclick="openChildWindow()" />
<div>Click me: nothing will happen.</div>
<div id="aaa" class="yourclass">
<p>This is a paragraph with a <span>span</span> where the paragraph's container has the class. Click the span or the paragraph and see what happens.</p>
This sentence is directly in the div with the class rather than in child element.
</div>
<div>Nothing for this div.</div>
<a>dsfsd</a>
</body>
</html>
**child.html:**
<html>
<head>
<title>Parent window document</title>
<script>
opener.document.body.onclick = function(e) {
var sender = (e && e.target) || (window.parent.event && window.parent.event.srcElement);
document.getElementById("id").value=sender.tagName;
}
</script>
</head>
<body>
<div id="child_wnd_doc_div_id">child window</div>
ID: <input type="text" id="id"/><br/>
Name: <input type="text" id="id"/><br/>
Xpath: <input type="text" id="id"/><br/>
CSS: <input type="text" id="id"/><br/>
</body>
</html>
Clearly, my concept is: I want to execute the child window function after changing the url in the parent window.
The only way I see:
observe the unload-event of the opener. When it fires, try(after a short timeout) to reassign the onclick-function(and also the onunlad-function).
Of course this will only work when both documents are placed under the same domain.
I m adding DropDown in jsp page.
and m trying to redirect a page exact after index change without any button click.
How can i add it to jsp page?
<script type="text/javascript" src="js/jquery-1.4.4.min.js"></script>
<script type="text/javascript">
$(function(){
$('com').bind('change', function () {
var value = $(this).val();
if(value==1) window.location = "servlet1?id=1";
if(value==2)window.location = "servlet1?id=2";
return false;
});
});
</script>
<body>
<select id="com">
<option></option>
<option value="1">Link1</option>
<option value="2">Link2</option>
</select></body>
Not working, is anything missing , plz
When i change index then i want to redirect to corresponding link/page.
Using jQuery you could do it as follows,
$(function(){
// bind change event to select
$('#ID_OF_select_ITEM').bind('change', function () {
var value = $(this).val(); // get selected value
window.location = someURL; // redirect based on the value
return false;
});
});
Just use '#com' instead of 'com' probably it will work
if still not working then let us know we have alternative for this task
I have a map that you can click on locations to get information for that area and I would like to show that information in a Iframe on the same page when clicked
My page has this for the link now
`<AREA SHAPE="CIRCLE" COORDS="555,142,6" HREF="http://www.Page.com" TITLE="" />`
Any suggestions
The beauty of AJAX is that you don't really need an IFRAME to do this.
You've got a server that will return to you information about a certain area. Each of the AREA tags simply needs an onclick attribute that calls a JavaScript function to retrieve that information and display it in a location you set aside on your page.
Here is a sample HTML page that will retrieve information from the server using AJAX
<html>
<head>
<script type="text/javascript">
function getAreaInfo(id)
{
var infoBox = document.getElementById("infoBox");
if (infoBox == null) return true;
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState != 4) return;
if (xhr.status != 200) alert(xhr.status);
infoBox.innerHTML = xhr.responseText;
};
xhr.open("GET", "info.php?id=" + id, true);
xhr.send(null);
return false;
}
</script>
<style type="text/css">
#infoBox {
border:1px solid #777;
height: 400px;
width: 400px;
}
</style>
</head>
<body onload="">
<p>AJAX Test</p>
<p>Click a link...
Area One
Area Two
Area Three
</p>
<p>Here is where the information will go.</p>
<div id="infoBox"> </div>
</body>
</html>
And here is the info.php that returns the information back to the HTML page:
<?php
$id = $_GET["id"];
echo "You asked for information about area #{$id}. A real application would look something up in a database and format that information using XML or JSON.";
?>
Hope this helps!