I have an external JavaScript file named paging.js. Following are the contents of the file:
function Pager(tableName,itemPerPage){
this.tableName = tableName;
this.itemPerPage = itemPerPage;
this.currentPage = 1;
this.pages = 0;
this.init()= function(){
alert("init called ");
var rows = document.getElementById(tableName).rows;
var records = (rows.length - 1);
this.pages = Math.ceil(records / itemPerPage);
}
this.showPageNav = function(pagerName,positionId){
alert("show page navi call");
var element = document.getElementById(positionId);
var pagerHtml = '<input src = "next.jpg" type="image">';
pagerHtml += '<input src = "next.jpg" type="image">' ;
element.innerHTML = pagerHtml;
}
}
Now I tried to call init from my jsp page like .
<script type="text/javascript">
var pager = new Pager('results',7);
pager.init();
</script>
This code i put before complete my body part in my jsp page.
For including this page I put line like
<script type="text/javascript"
src="${pageContext.request.contextPath}/js/paging.js"></script>
But i can't able to call init method. Is there anyone to help me for finding problem?
This line of code is the problem:
this.init()= function(){
Change it to:
this.init=function() {
Try
<script type="text/javascript"
src="js/paging.js"></script>
With .jsp 2.+ technology, I place all my links and scripts in a separate file that I reference using the <jsp:include> directive:
<jsp:include page="//path to your links_and_scripts page">
My links_and_scripts page has this meta and the path to my script:
<meta http-equiv="Content-Script-Type" content="application/javascript; charset=utf-8" />
<script src="// path to your scripts js"></script>
//...your other scripts and links here
Related
I'm generating pdf with wkhtmltopdf. There is a problem, that I cannot disable --footer-html on first THREE pages.
Below is java code for generating pdf:
pdf.addPageFromString(parseThymeleafTemplate());
pdf.addParam(new Param("--page-size", "A4", "-B", "35mm", "-L", "0", "-R", "0", "-T", "0"));
pdf.addParam(new Param("--footer-html", "/Users/kuanysh/IdeaProjects/pdf-report-sender/src/main/resources/templates/footer.html"));
And my footer.html
<!doctype html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<script>
function subst() {
var vars = {};
var x = document.location.search.substring(1).split('&');
for (var i in x) {
var z = x[i].split('=', 2);
vars[z[0]] = unescape(z[1]);
}
var x = ['frompage', 'topage', 'page', 'webpage', 'section', 'subsection', 'subsubsection'];
for (var i in x) {
var y = document.getElementsByClassName(x[i]);
for (var j = 0; j < y.length; ++j) y[j].textContent = vars[x[i]];
if (vars['page'] === 1) { // If page is 1, set FakeHeaders display to none
document.getElementById("stopFooter").style.display = 'none';
}
if (vars['page'] === 2) { // If page is 1, set FakeHeaders display to none
document.getElementById("stopFooter").style.display = 'none';
}
if (vars['page'] === 3) { // If page is 1, set FakeHeaders display to none
document.getElementById("stopFooter").style.display = 'none';
}
}
}
</script>
</head>
<body>
<div onload="subst()">
<footer class="footer" id="stopFooter">
<p>I am footer</p>
<div class="line"></div>
<p>Hello</p>
</footer>
</div></body>
</html>
And it's not working. Does wkhtmltodpf library give us some functions for that?
Remove onload="subst()" from the div.
Then change your function into a self invoking function by changing its opening and closing lines:
function subst() { becomes (function () {
and the last (closing) } becomes })();
Don't forget to remove the script from the head. Place it into the body below your div. Otherwise the script will run before the HTML get's loaded without having any effect.
I have a requirement in my application like,I need to open files(pdf,docx,pptx..)with in html(embedding into div or iframe) by passing document paths(urls) on click of a button.
I have tried opening the documents outside the application and its working,But I am stuck on hw to approach the above problem.
Thanks.
You can have a iframe inside a div and o0pen the document in that iframe element as follows:
<div>
<iframe src="" id="iframeRight" style="width:600px; height:500px;" frameborder="0">
</iframe>
</div>
In the controller, on click of button you can assign the base64 string of the document to iframe src as follows:
document.getElementById("iframeRight").src = base64String;
Just ensure that the base64 string has the metadata attached to it like for pdf it must start as:
data:application/pdf;base64,
PFB a demo program that lets user select the document and displays the same in the iframe. Copy paste in notepad and run this as html file. Select a doc less than 5 mb in size.
<!DOCTYPE html>
<html>
<body>
<input type="file" id="file-uploadUC" />
<iframe src="demo_iframe.htm" id="ifrm" height="200" width="300"></iframe>
<script>
document.getElementById("file-uploadUC").addEventListener("change", rdfile);
function rdfile() {
extn = '';
FileContentBase64 = '';
FileName = '';
if (this.files && this.files[0]) {
if (this.files[0].size <= 5347738) {
var FR = new FileReader();
FileName = this.files[0].name;
extn = FileName.split(".").pop();
FR.onload = function (e) {
FileContentBase64 = e.target.result;
document.getElementById("ifrm").src = FileContentBase64;
};
FR.readAsDataURL(this.files[0]);
}
else {
}
}
else {
}
}
</script>
</body>
</html>
I use at frontend AngularJS 1.4 and at Backend Java and I have a lot of options which can be selected in frontend, e.g. the country:
GERMANY
FRANCE
USA
RUSSIA
Enums are written in upper case and I will customize this in frontend (e.g. FRANCE will become to France).
My question now would be if there is a directive or a any other support doing this in frontend.
In view:
<select ng-model="selectedCountry" ng-options="country as country.name for country in countries | filter:filterUpperCamelCase"></select>
In controller:
$scope.countries= [
{name:"SPAIN"},
{name:"GERMANY"}
];
$scope.filterUpperCamelCase = function(element){
element.name = element.name.toLowerCase();
element.name = element.name.charAt(0).toUpperCase() + element.name.slice(1);
return element;
};
Check out this link
http://hello-angularjs.appspot.com/angularjs-create-custom-filter
It has a custom filter written which can help you out.
Here's code from link given above.
<!DOCTYPE html>
<html ng-app="HelloApp">
<head>
<title></title>
</head>
<body ng-controller="HelloCtrl">
<form>
<input type="text" ng-model="name"/>
</form>
<div>{\{name|titlecase}}</div>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script type="text/javascript">
// Code defining custom module consisting of a filter
// The module needs to be included as dependency for using the filter, titlecase
//
angular.module('CustomFilterModule', [])
.filter( 'titlecase', function() {
return function( input ) {
return input.replace(/\w\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});
}
});
// Angular App on this page
// Included CustomFilterModule as dependency
//
angular.module('HelloApp', [ 'CustomFilterModule'])
.controller('HelloCtrl', ['$scope', function($scope){
$scope.name = '';
}])
</script>
</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
%>
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.)