How to pass a variable from HTML to Java? - java

I want to pass a variable from HTML to Java. For this, I wrote the following code:
<!doctype html>
<html>
<title>How to create a typewriter or typing effect with jQuery</title>
<div id="example1">fsdfsdfojsdlk sdfj lskdhfk sdf </div>
<style>
body{
background: transparent;
color: #ec5a62;
}
#container{
font-size: 7em;
}
</style>
</head>
<body>
<div id="container"></div>
<!--
We use Google's CDN to serve the jQuery js libs.
To speed up the page load we put these scripts at the bottom of the page
-->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js"></script>
<script>
//define text
var text = ("document.getElementById("example1")");
//text is split up to letters
$.each(text.split(''), function(i, letter){
//we add 100*i ms delay to each letter
setTimeout(function(){
//we add the letter to the container
$('#container').html($('#container').html() + letter);
}, 30*i);
});
</script>
</body>
</html>
But it is not working. How can I achieve this?
Please do help me.
I'm using var text =("document.getElementById("example1")");
But its not working.

to get value use var x=document.getElementById("example1").value;
your code should be like this:
var text=document.getElementById("example1").value;
//text is split up to letters
$.each(text.split(''), function(i, letter){
//we add 100*i ms delay to each letter
setTimeout(function(){
//we add the letter to the container
$('#container').html($('#container').html() + letter);
}, 30*i);
});

Related

Pagination: how to load first page with AJAX

I'm writing online shopping application using Struts 2.
In front-end I'm using jsp, twitter bootstrap, jquery, moustache.js template, twbs pagination plugin and some javascript.
I have Product entity and I want to display the list of products to the user in jsp page.
The way I'm doing it is async loading page with fix number(20) of products in json format and then obtaining them using mustache template.
All my code works except the time when user the first time sees this jsp page - first 20 products are not displaying. So when I'm moving from page to page it loads info, but as twbs plugin works through firing events it means that event is not triggered after jsp page loaded the first time.
So my question is whats the truly good way to fix this ?
Should I fire an event once or use $(document).ready() or $(document).onload() ?
I'm not an expert in javascript, so please be patient
<html>
<%# include file="/WEB-INF/jspf/head.jspf"%>
<body>
<%# include file="/WEB-INF/jspf/menu.jspf"%>
<div class="container">
<ul class="sync-pagination pagination"></ul>
<div id="products" style="width: 50%"></div>
<ul class="sync-pagination pagination"></ul>
</div>
<script type="text/javascript"
src="webjars/mustachejs/0.8.2/mustache.js"></script>
<script id="products-template" type="text/mustache-template">
<ul class="list-group">
{{#.}}
<li class="list-group-item">
<label for="{{name}}">Name: /label> {{name}}
</br>
<label for="{{price}}">Price: </label> {{price}}
</br>
Full description...
</li>
{{/.}}
</ul>
</script>
<script type="text/javascript"
src="script/jquery.twbsPagination.min.js"></script>
<script type="text/javascript">
var records = "${requestScope.records}";
var recordsPerPage = 20;
var pages = Math.ceil(records / recordsPerPage);
$('.sync-pagination').twbsPagination({
totalPages : pages,
visiblePages : 7,
onPageClick : function(event, page) {
$('#products').html(changePage(page));
}
});
function changePage(page) {
pnumber = page || 1;
$.ajax({
type : 'GET',
dataType : 'json',
url : 'product/upload_products?page=' + pnumber,
success : function(products) {
var template = $('#products-template').html();
var info = Mustache.render(template, products);
$('#products').html(info);
}
})
}
</script>
</body>
</html>
You need to call changePage(); on the initial load. You might also want to call this when the page finishes loading everything by using $(document).ready();
<script type="text/javascript">
var records = "${requestScope.records}";
var recordsPerPage = 20;
var pages = Math.ceil(records / recordsPerPage);
$('.sync-pagination').twbsPagination({
totalPages : pages,
visiblePages : 7,
onPageClick : function(event, page) {
$('#products').html(changePage(page));
}
});
function changePage(page) {
pnumber = page || 1;
$.ajax({
type : 'GET',
dataType : 'json',
url : 'product/upload_products?page=' + pnumber,
success : function(products) {
var template = $('#products-template').html();
var info = Mustache.render(template, products);
$('#products').html(info);
}
})
}
//Add this in here
changePage();
</script>

Google charts with jstl forEach

Hi I am trying to render google chart on my java program. but it doesn't display at all. Google chart api is implemented in .jsp file. Since my java code delivers correct data (I checked with system print), there must be something wrong on my jsp file. specially [A] part..
I am very new to this world.
Can anyone point out what did I do wrong in .jsp file.
my jsp file
<html>
<head>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.DataTable();
data.addColumn('number', 'Data value');
data.addRows([
<c:forEach var="dataIntValue" items="${dataInt}">
['${dataIntValue}'], //---- [A]
</c:forEach>
]);
var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
chart.draw(data, {width: 600, height: 340, min: 0});
}
</script>
</head>
<body>
<div id="chart_div" style="width: 1000px; height: 540px;"></div>
</body>
</html>
Update
when I look at the page source on browser.. it shows like this..
<html>
<head>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.DataTable();
data.addColumn('number', 'Data Value');
data.addRows([
['100'],
['200'],
['300'],
['400'],
['500'],
['110'],
['120'],
['130'],
['140'],
['200'],
]);
var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
chart.draw(data, {width: 1000, height: 540, min: 0});
}
</script>
</head>
<body>
<div id="chart_div" style="width: 1000px; height: 540px;"></div>
</body>
</html>
and the values are right ones.. but I don't know it should be with this '' together.. Can that be problem? e.g. it shows this ['400'], but may be should like this [400] without ''? but I don't know why it is with ''? what did I do in my code... and why with '400'? not just the value 400...
update 2
applied the comment advice and then, get a syntax error , can't compile at all..
what I did based on advice: remove the ' ' in the [A]
so jsp file looks like this.. all same only [A] part is different by removing the ' '.
<html>
<head>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.DataTable();
data.addColumn('number', 'Data Value');
data.addRows([
<c:forEach var="dataIntValue" items="${dataInt}">
[${dataIntValue}], //---[A]
</c:forEach> //----[B]
]); //----[B]
var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
chart.draw(data, {width: 1000, height: 540, min: 0});
} //----- [c]
</script>
</head>
<body>
<div id="chart_div" style="width: 1000px; height: 540px;"></div>
</body>
</html>
These are the syntax errors.. what I get after removing ' ' from [A]
Multiple annotations found at this line:
- Syntax error on tokens, ArrayLiteralHeader expected
instead
- Syntax error, insert "]" to complete
MemberExpression
- Syntax error, insert ")" to complete Arguments
- Syntax error on tokens, delete these tokens
- Syntax error, insert "]" to complete ArrayLiteral
result here: can compile but no charts appears on browser: Comments from (JB Nizet)=> What you posted is not an error you get at runtime. It's an error that your IDE, which tries to interpret your code as pure JavaScript, generates. The code is correct. Deploy it, run it, ans see if it works
update 3 & solved: comma should be there in [A] and google chart code was problem should be like this:
working code:
1) changed to google.visualization.arrayToDataTable instead google.visualization.DataTable.
2) I was missing first column element in here (so should have 2 elements like this) ['${dataIntValue}', ${dataIntValue}], instead with only one element this was wrong: [${dataIntValue}],
Correct code=>
<html>
<head>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
//---[solution] modified from here
var data = google.visualization.arrayToDataTable([
['number', 'Data Value'],
<c:forEach var="dataIntValue" items="${dataInt}">
['${dataIntValue}', ${dataIntValue}],
</c:forEach>
]); //--- until here.
var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
chart.draw(data, {width: 600, height: 340, min: 0});
}
</script>
</head>
<body>
<div id="chart_div" style="width: 600px; height: 340px;"></div>
</body>
</html>

JTextPane getText() return html tag in different order

I am using JTextPane to store some HTML text:
private static final String HTML_STR = "<html><div>plot(<b><font color=#3775B9>X</font></b>,Y)</div><div>plot(<b><font color=#3775B9>X</font></b>,Y,LineSpec)</div></html>"
JTextPane textPane = new JTextPane();
textPane.setContentType("text/html");
textPane.setText(HTML_STR);
After that, every time I call the textPane.getText(). the html content will show the html tag in different order occasionally. Like:
sometimes, < b> is inside of < font>:
<head>
</head>
<body>
<div>
plot(<font color="#3775B9"><b>X</b></font>,Y)
</div>
<div>
plot(<font color="#3775B9"><b>X</b></font>,Y,LineSpec)
</div>
</body>
</html>
some other times, < font> is inside of < b>:
<head>
</head>
<body>
<div>
plot(<b><font color="#3775B9">X</font></b>,Y)
</div>
<div>
plot(<b><font color="#3775B9">X</font></b>,Y,LineSpec)
</div>
</body>
</html>
Can anybody explain a little bit for me why JTextPane behaviors like this? Is there any way to let JTextPane return the same order constantly?
Thanks!

how to display a stack of image followed by name in order

i wan to ask that if my machine got 1000/10000 of image and each image is named follow by order (1.jpg, 2.jpg, 3.jpg, 4.jpg .... 10000.jpg) , how to do it to let it display follow th order ?
i saw a lot of question on internet that they put it on the JLabel but many of them say it won't work . i have even try a few method to let it display like javascript but it is not the result i want.
I wish the program is running like 0.5 seconds a time and display the image followed the image number.
Can anyone guild me through this ? thanks in advance
==================================================================================
update : this is my javascript code
<html>
<head>
</head>
<body>
<img src="images/image1.jpg" alt="rotating image" width="600" height="500" id="rotator">
<script type="text/javascript">
(function() {
var rotator = document.getElementById('rotator'); // change to match image ID
//var imageDir = 'images/'; // change to match images folder
var delayInSeconds = 1; // set number of seconds delay
// list image names
var images = ['1.jpg','2.jpg', '3.jpg', '4.jpg'];
// don't change below this line
var num = 0;
var changeImage = function() {
var len = images.length;
rotator.src = images[num++];
if (num == len) {
num = 0;
}
};
setInterval(changeImage, delayInSeconds * 50);
})();
</script>
</body>
</html>
first of all, you need to preload images, to do it, you can add them in hidden div. Then replace your original image with it.Something like this:
<html>
<head>
<title>ViewImage</title>
<script type="text/javascript" src="/jquery-1.4.2.min.js"></script>
<script>
var img_num = 1;
$(function(){
window.setInterval(function(){
var img = $('#hiden-img');
if(img[0].complete==true)
$('#real-image').attr('src', img.attr('src'));
img_num++;
if(img_num>10000)img_num=1;
img.attr('src', '/img/'+img_num+'.jpg');
}, 500);
});
</script>
</head>
<body>
<img id="hiden-img" style="display:none;"/>
<img id="real-image" src="/img/1.jpg"/>
</body>
</html>
try it like this. Download jquery and place it in your site, replace paths "/path/to/img" (2 times) and "/path/to/jquery" to your real paths. this should do the trick.
you do not need to refresh page every second. You do not need to refresh it all.
It's works on my site.

html div expansion

In my project I need to expand my div section,when link is clicked,say "see more".
how can this be done?
Check the one which is in www.facebook.com,where each post has see more,if the div section cant contain the section...
This is the screenshot of what i have done
Code:
<div id="page" >
<div id="page-bgtop">
<div id="page-bgbtm">
<div id="content" style="min-height:400px" >
<div class="post" >
<h2 class="title">UPDATES</h2>
<%
try{
st1=con1.createStatement();
ResultSet rs=st1.executeQuery("select * from article ORDER BY artid DESC");
%>
<div style="width:450px; word-wrap: break-word;">
<%
while(rs.next())
{
String s=rs.getString("article");
out.println("<div>");
out.println("<p align ='justify' >"+s+"</p>");
out.println("<hr style='border:dashed #FFFFFF; border-width:1px 0 0 0; height:0;line-height:0px;font-size:0;margin:0;padding:0;'>");
out.println("</div>");
}
%>
</div>
<%
}catch(Exception e){
//System.out.println("exception is "+e);
e.printStackTrace();
}
%>
</div>
You should be able to expose/hide divs using the .show and .hide methods from JQuery as shown here.
Add a javascript function to onclick event of the link. In that javascript function, set the display property of the relevant div to display:hidden or display:block.
Or
You can set a initial height using CSS height property and set overflow-y:hidden
Then onclick of the relevant link, change the height of the div to see all of the content.

Categories