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>
Related
Can i use variable charity from th:each in another block of code. For example
<select class="select-field">
<option th:each="charity : ${charities}" th:value="${charity.id}" th:text="${charity.name}"></option>
</select>
<div>
<p th:text="${'You selected '+ charity.name}">
<div>
No, Thymeleaf is rendered on the server-side, so to accomplish this, you would need to use js or jQuery. Something like the code below should do the trick.
jQuery
$(document).ready(function() {
// If you want the option's text.
$('.select-field').on('change', function() {
$('p').text("You selected " + $(this).find('option:selected').text()));
})
// If you want the option's value.
$('.select-field').on('change', function() {
$('p').text("You selected " + $(this).val()));
})
})
UPDATE
If you would like to add more information from your charity object to your options, you could use th:attr. So, for example, if you want the charity's description and image name, then you could do something like the following.
HTML
<select class="select-field">
<option th:each="charity : ${charities}" th:value="${charity.id}" th:text="${charity.name}" th:attr="data-description=${charity.description}, data-image=${charity.image}"></option>
</select>
Then, you could just get each attribute value using jQuery .attr() function.
$(document).ready(function() {
$('.select-field').on('change', function() {
var selectedOption = $(this).find('option:selected');
var name = $(selectedOption).text();
var id = $(selectedOption).val();
var description = $(selectedOption).attr('data-description');
var imageName = $(selectedOption).attr('data-image');
// Find your image by id.
var image = $('#myImage');
// Set your new image.
$(image).attr('src','/img/'+ imageName));
})
})
In HTML, you can make following change to div tag:
<div class="display-class">
<p></p>
<div>
This will help identify particular div
Then you can use jQuery to display the name of the selected option.
<script type="text/javascript">
$('.select-field').on("change", function() {
var selectedOption = $(this).find('option:selected').text();
$div = $('.display-class');
$p = $div.find('p');
$p.text("You selected: " + selectedOption);
});
</script>
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);
});
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>
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.
I want to make an image viewer (for my website) like the one in Facebook (the old one). When the user click the next or back arrow it will change the picture and the URL of the page.
This is an example of what I want (http://www.facebook.com/pages/Forest-Ville/307556775942281)
Most importantly I want the page to reload with each click with new (URL, comment box, ads, etc.) I do not want to use any Cookies.
Now I am using this, but its completely different from what I want.
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<script language="JavaScript">
var NumberOfImages = 10
var img = new Array(NumberOfImages)
img[0] = "http://damnthisfunny.site40.net/1.jpg"
img[1] = "http://damnthisfunny.site40.net/2.jpg"
img[2] = "http://damnthisfunny.site40.net/3.jpg"
img[3] = "http://damnthisfunny.site40.net/4.jpg"
img[4] = "http://damnthisfunny.site40.net/5.jpg"
img[5] = "http://damnthisfunny.site40.net/6.jpg"
img[6] = "http://damnthisfunny.site40.net/7.jpg"
img[7] = "http://damnthisfunny.site40.net/8.jpg"
img[8] = "http://damnthisfunny.site40.net/9.jpg"
img[9] = "http://damnthisfunny.site40.net/10.jpg"
var imgNumber = 0
function NextImage()
{
imgNumber++
if (imgNumber == NumberOfImages)
imgNumber = 0
document.images["VCRImage"].src = img[imgNumber]
}
function PreviousImage()
{
imgNumber--
if (imgNumber < 0)
imgNumber = NumberOfImages - 1
document.images["VCRImage"].src = img[imgNumber]
}
</script>
<body>
<center>
<img name="VCRImage" src="http://damnthisfunny.site40.net/1.jpg" /></dr>
<br />
<a href="javascript:PreviousImage()">
<img border="0" src="left1.jpg" /></a>
<a href="javascript:NextImage()">
<img border="0" src="right1.jpg" /></a>
</center>
</body>
</html>
Any ideas ?