How to call a JavaScript function from java code android native - java
I need to load a HTML file which internally has some AJAX service calls.
I need to call a function in that HTML file from Java code.
I can see the data loading in web but not in Emulator.
My HTML file is below
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, user-scalable=yes">
<link class="include" rel="stylesheet" type="text/css"
href="./jquery.jqplot.min.css" />
<link type="text/css" rel="stylesheet"
href="syntaxhighlighter/styles/shCoreDefault.min.css" />
<link type="text/css" rel="stylesheet"
href="syntaxhighlighter/styles/shThemejqPlot.min.css" />
<script class="include" type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
</head>
<body>
<script class="include" type="text/javascript"
src="./jquery.jqplot.min.js"></script>
<script type="text/javascript"
src="syntaxhighlighter/scripts/shCore.min.js"></script>
<script type="text/javascript"
src="syntaxhighlighter/scripts/shBrushJScript.min.js"></script>
<script type="text/javascript"
src="syntaxhighlighter/scripts/shBrushXml.min.js"></script>
<!-- End Don't touch this! -->
<!-- Additional plugins go here -->
<script class="include" language="javascript" type="text/javascript"
src="./plugins/jqplot.dateAxisRenderer.min.js"></script>
<script class="include" language="javascript" type="text/javascript"
src="./plugins/jqplot.ohlcRenderer.min.js"></script>
<script class="include" language="javascript" type="text/javascript"
src="./plugins/jqplot.highlighter.min.js"></script>
<script type="text/javascript" src="./plugins/jqplot.dateAxisRenderer.min.js"></script>
<script type="text/javascript" src="./plugins/jqplot.canvasTextRenderer.min.js"></script>
<script type="text/javascript" src="./plugins/jqplot.canvasAxisTickRenderer.min.js"></script>
<script type="text/javascript" src="./plugins/jqplot.categoryAxisRenderer.min.js"></script>
<script type="text/javascript" src="./plugins/jqplot.barRenderer.min.js"></script>
<script type="text/javascript" src="./plugins/jqplot.cursor.min.js"></script>
<script class="code" language="javascript" type="text/javascript">
var arr = [];
var arr1 = [];
var jsonstr;
$(document).ready(function() {
$.jqplot.config.enablePlugins = true;
$("#status").html("Loading...");
$("#status").animate({opacity: 1,top: "200px"},200);
});
function getData(symbolId,timeLine,type){
//$("#mydiv").html(symbolId +" "+timeLine+" "+type);
$.ajax({
url: 'http://83.101.141.1:8020/mTadawul/TadawulService.svc/GetOHLCData?Symbol='+symbolId+'&Char='+timeLine,
dataType: 'json',
async: false,
success: function(data) {
jsonstr = jsontoarray(eval (data));
/*Custom Code to check the data*/
if(data != "")
{$("#status").animate({opacity: 0,top: "-50px"},200);createChart(type, timeLine);}else{$("#status").html("No Data");$("#status").animate({opacity: 1,top: "200px"},200);}
}
});
//$.getJSON('http://183.82.0.37:8080/TadawulWCFService/TadawulService.svc/GetOHLCData?Symbol=1010&Char='+timeLine, function(data) {
//});
return 1;
}
function jsontoarray(jsonstr){
var arrayl = [];
for (var i = 0; i < jsonstr.length; i++) {
var values = new Array();
values[0] = jsonstr[i].TimeStamp.replace("T"," ").replace("nm","");
values[1] = jsonstr[i].Open;
values[2] = jsonstr[i].High;
values[3] = jsonstr[i].Low;
values[4] = jsonstr[i].Close;
arrayl.push(values);
}
return arrayl;
}
function createChart(type, timeLine) {
timeLine = typeof timeLine !== 'undefined' ? timeLine : 'M';
console.log(jsonstr);
var charts = [{
name: "chart2",
seriesDefaults: {
yaxis: 'y2axis'
},
axes: {
xaxis: {
renderer: $.jqplot.DateAxisRenderer,
numberTicks:36,
tickOptions: {
formatString: '%b %e %Y ',
angle:-90
},
tickRenderer:$.jqplot.CanvasAxisTickRenderer,
labelOptions:{
fontFamily:'Arial',
fontSize: '14pt'
},
labelRenderer: $.jqplot.CanvasAxisLabelRenderer
},
},
series: [{
renderer: $.jqplot.OHLCRenderer,
rendererOptions: {
candleStick: true
}
}],
highlighter: {
show: true,
showMarker: true,
tooltipAxes: 'xy',
yvalues: 4,
formatString: '<table class="jqplot-highlighter"> \<tr><td>date:</td><td>%s</td></tr> \<tr><td>open:</td><td>%s</td></tr> \<tr><td>high:</td><td>%s</td></tr> \<tr><td>low:</td><td>%s</td></tr> \<tr><td>close:</td><td>%s</td></tr></table>'
},
data: [jsonstr]
}];
if(type == "line"){
charts[0].series[0]={};
}
else if(type == "bar"){
charts[0].series[0].rendererOptions = {smooth : true};
}else
{
charts[0].series[0].rendererOptions = {candleStick : true};
}
if(timeLine == 'H'){
charts[0].axes.xaxis.tickOptions = { formatString: '%b %e %#I %p',
angle:-90};
//charts[0].axes.xaxis['tickInterval'] = "1 hour";
}
$('#chart2').jqplot(charts[0]);
}
</script>
<div id="mydiv"></div>
<label id="lbl"></label>
<div class="test" style="position:absolute; top:-50px; left:40%; color:#333333; opacity:0;z-index:9999;" id="status">No Data</div>
<div id="chart2" style="height: 400px; width: 720px;">
</div>
In that code I need to call getData() passing 3 parameters from Java code.
My Java code is below:
webView.addJavascriptInterface(new JavaScriptInterface(this), "Android");
String loc = "file:///android_asset/candlechart/candlebar.html";
webView.getSettings().setJavaScriptEnabled(true);
webView.clearView();
// myWebView.measure(100, 100);
webView.getSettings().setUseWideViewPort(true);
webView.getSettings().setLoadWithOverviewMode(true);
webView.loadUrl(loc);
webView.loadUrl("javascript:getData('1020','M','bar')");
webView.setWebViewClient(new WebViewClient() {
public void onPageFinished(WebView view, String loc) {
}
});
You are calling your second loadUrl() way too soon. loadUrl() is asynchronous. You need to wait until your page is loaded. Call webView.loadUrl("javascript:getData('1020','M','bar')"); in the OnPageFinished method.
Related
Spring Boot + Swagger + custom swagger-ui.html
I've got problems migrating a war application to a spring boot jar application. I'm using spring boot 1.4.1 and swagger 2.6.0. To customize swagger ui in a war you have to put a custom swagger-ui.html to /webapp directory. In spring boot it is not recommend to use the webapp directory because it does not work in a bundled jar. But putting a custom swagger-ui.html to /resources/static will be ignored by swagger. Is there any simple solution (instead of adding the whole swagger distribution to my application)? My custom swagger-ui.html looks like <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>API</title> <link rel="icon" type="image/png" href="webjars/springfox-swagger-ui/images/favicon-32x32.png" sizes="32x32"/> <link rel="icon" type="image/png" href="webjars/springfox-swagger-ui/images/favicon-16x16.png" sizes="16x16"/> <link href='webjars/springfox-swagger-ui/css/typography.css' media='screen' rel='stylesheet' type='text/css'/> <link href='webjars/springfox-swagger-ui/css/reset.css' media='screen' rel='stylesheet' type='text/css'/> <link href='webjars/springfox-swagger-ui/css/screen.css' media='screen' rel='stylesheet' type='text/css'/> <link href='webjars/springfox-swagger-ui/css/reset.css' media='print' rel='stylesheet' type='text/css'/> <link href='webjars/springfox-swagger-ui/css/print.css' media='print' rel='stylesheet' type='text/css'/> <script src='webjars/springfox-swagger-ui/lib/jquery-1.8.0.min.js' type='text/javascript'></script> <script src='webjars/springfox-swagger-ui/lib/jquery.slideto.min.js' type='text/javascript'></script> <script src='webjars/springfox-swagger-ui/lib/jquery.wiggle.min.js' type='text/javascript'></script> <script src='webjars/springfox-swagger-ui/lib/jquery.ba-bbq.min.js' type='text/javascript'></script> <script src='webjars/springfox-swagger-ui/lib/handlebars-2.0.0.js' type='text/javascript'></script> <script src='webjars/springfox-swagger-ui/lib/underscore-min.js' type='text/javascript'></script> <script src='webjars/springfox-swagger-ui/lib/backbone-min.js' type='text/javascript'></script> <script src='webjars/springfox-swagger-ui/swagger-ui.min.js' type='text/javascript'></script> <script src='webjars/springfox-swagger-ui/lib/highlight.7.3.pack.js' type='text/javascript'></script> <script src='webjars/springfox-swagger-ui/lib/jsoneditor.min.js' type='text/javascript'></script> <script src='webjars/springfox-swagger-ui/lib/marked.js' type='text/javascript'></script> <script src='webjars/springfox-swagger-ui/lib/swagger-oauth.js' type='text/javascript'></script> <script src='webjars/springfox-swagger-ui/springfox.js' type='text/javascript'></script> <style> .swagger-section #header { background-color: #ff5722; } </style> </head> <body class="swagger-section"> <div id='header'> <div class="swagger-ui-wrap"> <a id="logo" href="http://www.my-app.com">my-app.com API</a> <form id='api_selector'> <div class='input' style="display: none"> <select id="select_baseUrl" name="select_baseUrl"/> </div> <div class='input'><input placeholder="http://example.com/api" id="input_baseUrl" name="baseUrl" type="text"/> </div> <!-- <div class='input'><input placeholder="Enter authorization token" id="input_apiKey" name="apiKey" type="text"/></div> <div class='input' style="display: none"><a id="explore" href="#" data-sw-translate>Explore</a></div> --> </form> </div> </div> <script type="text/javascript"> function addApiKeyAuthorization() { var key = $('#input_apiKey')[0].value; console.log("key: " + key); if (key && key.trim() != "") { var apiKeyAuth = new SwaggerClient.ApiKeyAuthorization("Authorization", key, "header"); window.swaggerUi.api.clientAuthorizations.add("bearer", apiKeyAuth); //window.authorizations.add("Authorization", new ApiKeyAuthorization("Authorization", key, "query")); console.log("Set authorization token: " + key); } } $('#input_apiKey').change(function () { addApiKeyAuthorization(); }); </script> <div id="message-bar" class="swagger-ui-wrap" data-sw-translate> </div> <div id="swagger-ui-container" class="swagger-ui-wrap"></div> </body> </html>
I have found this simple way to customize Swagger into a Spring Boot application with just two files copied from original springfox-swagger-ui First of all i have disabled #Configuration from SwaggerConfig.java: //#Configuration <-- Attention, disable Configuration #EnableSwagger2 public class SwaggerConfig { #Bean public Docket productApi() { return new Docket(DocumentationType.SWAGGER_2) .ignoredParameterTypes(Pageable.class) .select().apis(RequestHandlerSelectors.any()) .paths(regex("/v1/.*")) .build(); } } Then I have extended a WebMvcConfigurerAdapter: #Configuration #Import(SwaggerConfig.class) public class MvcConfig extends WebMvcConfigurerAdapter { #Override public void addResourceHandlers(final ResourceHandlerRegistry registry) { registry.addResourceHandler("/doc/v1/**").addResourceLocations("classpath:/doc/v1/"); registry.addResourceHandler("/doc/v1/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/"); } } Then I have just copied original file swagger-ui.html into src/main/resources/doc/v1/api.html with just a simple modification. I have substituted this line: <script src='webjars/springfox-swagger-ui/springfox.js' type='text/javascript'></script> with this line: <script src='js/swagger.js' type='text/javascript'></script> This is my api.html <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Swagger UI</title> <link rel="icon" type="image/png" href="webjars/springfox-swagger-ui/images/favicon-32x32.png" sizes="32x32"/> <link rel="icon" type="image/png" href="webjars/springfox-swagger-ui/images/favicon-16x16.png" sizes="16x16"/> <link href='webjars/springfox-swagger-ui/css/typography.css' media='screen' rel='stylesheet' type='text/css'/> <link href='webjars/springfox-swagger-ui/css/reset.css' media='screen' rel='stylesheet' type='text/css'/> <link href='webjars/springfox-swagger-ui/css/screen.css' media='screen' rel='stylesheet' type='text/css'/> <link href='webjars/springfox-swagger-ui/css/reset.css' media='print' rel='stylesheet' type='text/css'/> <link href='webjars/springfox-swagger-ui/css/print.css' media='print' rel='stylesheet' type='text/css'/> <script src='webjars/springfox-swagger-ui/lib/object-assign-pollyfill.js' type='text/javascript'></script> <script src='webjars/springfox-swagger-ui/lib/jquery-1.8.0.min.js' type='text/javascript'></script> <script src='webjars/springfox-swagger-ui/lib/jquery.slideto.min.js' type='text/javascript'></script> <script src='webjars/springfox-swagger-ui/lib/jquery.wiggle.min.js' type='text/javascript'></script> <script src='webjars/springfox-swagger-ui/lib/jquery.ba-bbq.min.js' type='text/javascript'></script> <script src='webjars/springfox-swagger-ui/lib/handlebars-4.0.5.js' type='text/javascript'></script> <script src='webjars/springfox-swagger-ui/lib/lodash.min.js' type='text/javascript'></script> <script src='webjars/springfox-swagger-ui/lib/backbone-min.js' type='text/javascript'></script> <script src='webjars/springfox-swagger-ui/swagger-ui.min.js' type='text/javascript'></script> <script src='webjars/springfox-swagger-ui/lib/highlight.9.1.0.pack.js' type='text/javascript'></script> <script src='webjars/springfox-swagger-ui/lib/highlight.9.1.0.pack_extended.js' type='text/javascript'></script> <script src='webjars/springfox-swagger-ui/lib/jsoneditor.min.js' type='text/javascript'></script> <script src='webjars/springfox-swagger-ui/lib/marked.js' type='text/javascript'></script> <script src='webjars/springfox-swagger-ui/lib/swagger-oauth.js' type='text/javascript'></script> <script src='js/springfox.js' type='text/javascript'></script> </head> <body class="swagger-section"> <div id='header'> <div class="swagger-ui-wrap"> <a id="logo" href="http://swagger.io"><img class="logo__img" alt="swagger" height="30" width="30" src="webjars/springfox-swagger-ui/images/logo_small.png" /><span class="logo__title">swagger</span></a> <form id='api_selector'> <div class='input'> <select id="select_baseUrl" name="select_baseUrl"/> </div> <div class='input'><input placeholder="http://example.com/api" id="input_baseUrl" name="baseUrl" type="text"/></div> <div id='auth_container'></div> <div class='input'><a id="explore" class="header__btn" href="#" data-sw-translate>Explore</a></div> </form> </div> </div> <div id="message-bar" class="swagger-ui-wrap" data-sw-translate> </div> <div id="swagger-ui-container" class="swagger-ui-wrap"></div> </body> </html> After that i have copied original springfox.js into src/main/resources/doc/v1/js/springfox.js where i have changed these lines: "baseUrl": function() { var urlMatches = /(.*)\/swagger-ui.html.*/.exec(window.location.href); return urlMatches[1]; }, with these lines: "baseUrl": function() { return window.location.origin; }, This is my complete springfox.js $(function() { var springfox = { "baseUrl": function() { return window.location.origin; }, "securityConfig": function(cb) { $.getJSON(this.baseUrl() + "/swagger-resources/configuration/security", function(data) { cb(data); }); }, "uiConfig": function(cb) { $.getJSON(this.baseUrl() + "/swagger-resources/configuration/ui", function(data) { cb(data); }); } }; window.springfox = springfox; window.oAuthRedirectUrl = springfox.baseUrl() + '/webjars/springfox-swagger-ui/o2c.html'; window.springfox.uiConfig(function(data) { window.swaggerUi = new SwaggerUi({ dom_id: "swagger-ui-container", validatorUrl: data.validatorUrl, supportedSubmitMethods: data.supportedSubmitMethods || ['get', 'post', 'put', 'delete', 'patch'], docExpansion: data.docExpansion || 'none', jsonEditor: JSON.parse(data.jsonEditor) || false, apisSorter: data.apisSorter || 'alpha', defaultModelRendering: data.defaultModelRendering || 'schema', showRequestHeaders: data.showRequestHeaders || true, timeout: data.requestTimeout, onComplete: function(swaggerApi, swaggerUi) { initializeSpringfox(); if (window.SwaggerTranslator) { window.SwaggerTranslator.translate(); } $('pre code').each(function(i, e) { hljs.highlightBlock(e) }); }, onFailure: function(data) { log("Unable to Load SwaggerUI"); }, }); initializeBaseUrl(); function addApiKeyAuthorization(security) { var apiKeyVehicle = security.apiKeyVehicle || 'query'; var apiKeyName = security.apiKeyName || 'api_key'; var apiKey = security.apiKey || ''; if (apiKey && apiKey.trim() != "") { var apiKeyAuth = new SwaggerClient.ApiKeyAuthorization(apiKeyName, apiKey, apiKeyVehicle); window.swaggerUi.api.clientAuthorizations.add(apiKeyName, apiKeyAuth); log("added key " + apiKey); } } function log() { if ('console' in window) { console.log.apply(console, arguments); } } function oAuthIsDefined(security) { return security.clientId && security.clientSecret && security.appName && security.realm; } function initializeSpringfox() { var security = {}; window.springfox.securityConfig(function(data) { security = data; addApiKeyAuthorization(security); if (typeof initOAuth == "function" && oAuthIsDefined(security)) { initOAuth(security); } }); } }); $('#select_baseUrl').change(function() { window.swaggerUi.headerView.trigger('update-swagger-ui', { url: $('#select_baseUrl').val() }); }); function maybePrefix(location, withRelativePath) { var pat = /^https?:\/\//i; if (pat.test(location)) { return location; } return withRelativePath + location; } function initializeBaseUrl() { var relativeLocation = springfox.baseUrl(); $('#input_baseUrl').hide(); $.getJSON(relativeLocation + "/swagger-resources", function(data) { var $urlDropdown = $('#select_baseUrl'); $urlDropdown.empty(); $.each(data, function(i, resource) { var option = $('<option></option>') .attr("value", maybePrefix(resource.location, relativeLocation)) .text(resource.name + " (" + resource.location + ")"); $urlDropdown.append(option); }); $urlDropdown.change(); }); } }); This is my folder structure Now you have just to run application and go to http://localhost:8080/doc/v1/api.html
Solution if you are using maven: You should copy swagger-ui.html into src/main/webapp Make your editions or replace screen.css by your theme.css Than add these code into your pom.xml: <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-war-plugin</artifactId> <configuration> <webResources> <resource> <directory>${basedir}/src/main/webapp</directory> <filtering>true</filtering> <includes> <include>*.css</include> <include>*.html</include> </includes> </resource> </webResources> </configuration> </plugin> </plugins> </build>
How to create editable combobox with database?
I am new to java and want to create an editable combobox in which when user types in it the results come from database. Like if I type "e" in combobox then all the name starting with "e" should come from database. Please give a simple example.
You can use jQuery plugins, following example is for php just replace the php parts with java code, or have a look at this. With JSON $(document).ready(function() { $(function() { $("#search").autocomplete({ source : function(request, response) { $.ajax({ url : "SearchController", type : "GET", data : { term : request.term }, dataType : "json", success : function(data) { response(data); } }); } }); }); }); With DB <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title>jQuery UI Autocomplete - Remote datasource</title> <link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css"> <script src="//code.jquery.com/jquery-1.10.2.js"></script> <script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script> <link rel="stylesheet" href="/resources/demos/style.css"> <style> .ui-autocomplete-loading { background: white url("images/ui-anim_basic_16x16.gif") right center no-repeat; } </style> <script> $(function() { function log( message ) { $( "<div>" ).text( message ).prependTo( "#log" ); $( "#log" ).scrollTop( 0 ); } $( "#birds" ).autocomplete({ source: "search.php", minLength: 2, select: function( event, ui ) { log( ui.item ? "Selected: " + ui.item.value + " aka " + ui.item.id : "Nothing selected, input was " + this.value ); } }); }); </script> </head> <body> <div class="ui-widget"> <label for="birds">Birds: </label> <input id="birds"> </div> <div class="ui-widget" style="margin-top:2em; font-family:Arial"> Result: <div id="log" style="height: 200px; width: 300px; overflow: auto;" class="ui-widget-content"></div> </div> </body> </html>
dynamic fields using jquery in jtable
here the fields are hard coded but i want to get the fields dynamically for my task,like i will have a list in this jsp which contains field names eg: list=[id,name,salary,doj] this list may change for new requests. Can i have some ideas to do this fields: { PersonId: { key: true, create: false, edit: false, list: false }, Name: { title: 'Author Name', width: '40%' }, Age: { title: 'Age', width: '20%' }, Watch: { title: 'Watch', width: '20%', display: function (data) { return ''; }, RecordDate: { title: 'Record date', width: '30%', type: 'date', create: false, edit: false } } });
You can build Javascript code dynamically on server side. For client side, you can also create fields dynamically. var fields = { PersonId: { //I assume that this field is standard key: true, list: false } }; if(someCondition) { fields['Name'] = { title: 'Author Name', width: '40%' }; } //Add other dynamic fields $('#PersonTableContainer').jtable({ title: 'Table of people', actions: { listAction: '/GettingStarted/PersonList', createAction: '/GettingStarted/CreatePerson', updateAction: '/GettingStarted/UpdatePerson', deleteAction: '/GettingStarted/DeletePerson' }, fields: fields }); In your condition, you can add fields from a list surely.
I was posting whole code by taking reference of above answer <%#page import="java.util.ArrayList"%> <%#page import="java.util.List"%> <%# page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>Setup and Load Data to jTable using Servlets and JSP</title> <!-- Include one of jTable styles. --> <link href="css/metro/crimson/jtable.css" rel="stylesheet" type="text/css" /> <link href="css/jquery-ui-1.10.3.custom.css" rel="stylesheet" type="text/css" /> <!-- Include jTable script file. --> <script src="js/jquery-1.8.2.js" type="text/javascript"></script> <script src="js/jquery-ui-1.10.3.custom.js" type="text/javascript"></script> <script src="js/jquery.jtable.js" type="text/javascript"></script> <script type="text/javascript"> <% List<String> strList = new ArrayList<String>(); strList.add("one"); strList.add("two"); strList.add("three"); %> var jsArray = [<% for (int i = 0; i < strList.size(); i++) { %>"<%= strList.get(i) %>"<%= i + 1 < strList.size() ? ",":"" %><% } %>]; var fields = { }; var arrayLength = jsArray.length; for(var i=0;i<arrayLength;i++) { fields[jsArray[i]] = { title: jsArray[i], width: '40%' }; } $(document).ready(function () { $('#PersonTableContainer').jtable({ title: 'Table of people', actions: { listAction: 'CRUDController?action=list', createAction:'CRUDController?action=create', updateAction: 'CRUDController?action=update', deleteAction: 'CRUDController?action=delete' }, fields:fields }); $('#PersonTableContainer').jtable('load'); }); </script> </head> <body> <div style="width:60%;margin-right:20%;margin-left:20%;text-align:center;"> <div id="PersonTableContainer"></div> </div> </body> </html>
How to print google-annotated-chart by clicking on print button, just like normal print as save it as a pdf programatically?
How to print Google annotated chart by clicking on print button in a web page? In my code, I used window.print() method, but when I print the page, chart disappears from the webpage and rest of the content is printing. Please help me. <!DOCTYPE html> <html> <head> <title>Google Chart with jsp Mysql Json</title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css"><!-- css for datepicker --> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> <script type="text/javascript" src="https://www.google.com/jsapi"></script> <script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script><!-- Javascript for datepicker --> <script type="text/javascript"> google.load("visualization", "1", {packages:["corechart"]}); $(document).ready(function(){ showGoogleChart('2013-12-01','2013-12-31'); //============================= Onpage load calling chart function $( "#from" ).datepicker({ changeMonth: true, dateFormat:'yy-mm-dd', numberOfMonths: 3, onClose: function( selectedDate ) { $( "#to" ).datepicker( "option", "minDate", selectedDate ); } }); $( "#to" ).datepicker({ dateFormat:'yy-mm-dd', changeMonth: true, numberOfMonths: 3, onClose: function( selectedDate ) { $( "#from" ).datepicker( "option", "maxDate", selectedDate ); } }); }); //==================== OnChange date call google chart ================== function getChartdate(){ alert("hi"); var startdate = $('#from').val(); var enddate = $('#to').val(); showGoogleChart(startdate,enddate); //===========On button click calling chart function========= } function showGoogleChart(startdate,enddate){ var queryObject=""; var queryObjectLen=""; var postdata = {"startDate":startdate,"endDate":enddate}; $.ajax({ type : 'POST', url : 'testPages.jsp', data:postdata, dataType:'json', success : function(data) { queryObject = eval('(' + JSON.stringify(data) + ')'); queryObjectLen = queryObject.empdetails.length; google.setOnLoadCallback(drawChart(queryObject,queryObjectLen)); }, error : function(xhr, type) { alert('server error occoured') } }); } function drawChart(queryObject,queryObjectLen) { var data = new google.visualization.DataTable(); data.addColumn('string', 'date'); data.addColumn('number', 'temp'); for(var i=0;i<queryObjectLen;i++) { var name = queryObject.empdetails[i].date; var empid = queryObject.empdetails[i].temp; data.addRows([ [name,parseInt(empid)] ]); } var options = { title: 'Employee Information', }; var chart = new google.visualization.LineChart(document.getElementById('chart_div')); chart.draw(data,options); } </script> </head> <body> <div style="margin: 50px;"> <label for="from">From</label> <input type="text" id="from" name="from"> <label for="to">to</label> <input type="text" id="to" name="to"> <input type="button" id="changeChart" onclick="getChartdate();" value="Change Chart"/> </div> <div id="chart_div"></div> </body> </html>
The method window print() will simply open the print dialog. How the page is formatted for print depends on how the browser formats webpages and the print stylesheet if present. Assuming the chart is some kind of image (or canvas), it might be that the browser choses to strip images when printing. Especially if the image is added using css background-image: url(...) because it assumes a background image (like background-color) is just for decoration and would waste ink if printed. A plain img tag should print though in most cases unless some css is removing it for print...
datepicker not working for jqgrid
I am not able to add DatePicker to the jqGrid, Following is my code. <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>My Date time example</title> <script src="js/jquery-1.7.2.min.js" type="text/javascript"></script> <link href="js/jquery-ui-1.9.2.custom.css" rel="stylesheet" type="text/css" /> <link href="css/ui.jqgrid.css" rel="stylesheet" type="text/css" /> <link rel="stylesheet" type="text/css" media="screen" href="css/ui.datepicker.css" /> <link href="css/ui.multiselect.css" rel="stylesheet" type="text/css" /> <script src="js/grid.locale-en.js" type="text/javascript"></script> <script src="js/jquery.jqGrid.min.js" type="text/javascript"></script> <link href="css/jquery.ui.theme.css" rel="stylesheet" type="text/css" /> <link href="css/jquery-ui.css" rel="stylesheet" type="text/css" /> <link rel="stylesheet" type="text/css" href="css/style.css"> <link rel="stylesheet" type="text/css" media="screen" href="css/jquery.ui.datepicker.css"/> </head> <script> var lastsel3; function FillGridOnEvent() { jQuery("#rowed6").jqGrid({ datatype: "local", height: 250, colNames:['ID Number','Last Sales','Name', 'Stock', 'Ship via','Notes'], colModel:[ {name:'id',index:'id', width:90, sorttype:"int", editable: true}, {name:'sdate',index:'sdate',width:90, editable:true, sorttype:"date",editoptions:{ dataInit: function(el) { setTimeout(function() { $(el).datepicker(); }, 200); }}}, {name:'name',index:'name', width:150,editable: true,editoptions{size:"20",maxlength:"30"}}, {name:'stock',index:'stock', width:60, editable: true,edittype:"checkbox",editoptions: {value:"Yes:No"}}, {name:'ship',index:'ship', width:90, editable: true,edittype:"select",editoptions: {value:"FE:FedEx;IN:InTime;TN:TNT;AR:ARAMEX"}}, {name:'note',index:'note', width:200, sortable:false,editable: true,edittype:"textarea", editoptions:{rows:"2",cols:"10"}}, ], onSelectRow: function(id){ if(id && id!==lastsel3){ jQuery('#rowed6').jqGrid('restoreRow',lastsel3); jQuery('#rowed6').jqGrid('editRow',id,true,pickdates); lastsel3=id; } }, editurl: "/MyServletNameHere", caption: "Date Picker Integration" }); var mydata3 = [ {id:"12345",name:"Desktop Computer",note:"note",stock:"Yes",ship:"FedEx", sdate:"2007-12-03"}, {id:"23456",name:"Laptop",note:"Long text ",stock:"Yes",ship:"InTime",sdate:"2007-12-03"}, {id:"34567",name:"LCD Monitor",note:"note3",stock:"Yes",ship:"TNT",sdate:"2007-12-03"}, {id:"45678",name:"Speakers",note:"note",stock:"No",ship:"ARAMEX",sdate:"2007-12-03"}, {id:"56789",name:"Laser Printer",note:"note2",stock:"Yes",ship:"FedEx",sdate:"2007-12-03"}, {id:"67890",name:"Play Station",note:"note3",stock:"No", ship:"FedEx",sdate:"2007-12-03"}, {id:"76543",name:"MobileTelephone", note:"note", stock:"Yes", ship:"ARAMEX", sdate:"2007-12-03"}, {id:"87654",name:"Server",note:"note2",stock:"Yes",ship:"TNT",sdate:"2007-12-03"}, {id:"98765",name:"Matrix Printer",note:"note3",stock:"No", ship:"FedEx",sdate:"2007-12-03"} ]; for(var i=0;i < mydata3.length;i++) jQuery("#rowed6").jqGrid('addRowData',mydata3[i].id,mydata3[i]); } function pickdates(id){ jQuery("#"+id+"_sdate","#rowed6").datepicker({dateFormat:"yy-mm-dd"}); } </script> <body> <body onload="FillGridOnEvent();"> <table id="rowed6"></table> </body> </html> when above code executes, it shows the output, but it does not show the datepicker in the sdate column. Please let me khow if I am wrong somewhere in the code! I think i have done a silly mistake, but not able to find it! Update Following is working example of datepicker using jqGrid, Following is working Example of datepicker using jqGrid.. <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>My Date time example</title> <script src="js/jquery-1.7.2.min.js" type="text/javascript"></script> <link href="js/jquery-ui-1.9.2.custom.css" rel="stylesheet" type="text/css" /> <link href="css/ui.jqgrid.css" rel="stylesheet" type="text/css" /> <link rel="stylesheet" type="text/css" media="screen" href="css/ui.datepicker.css" /> <link href="css/ui.multiselect.css" rel="stylesheet" type="text/css" /> <script src="js/grid.locale-en.js" type="text/javascript"></script> <script src="js/jquery.jqGrid.min.js" type="text/javascript"></script> <link href="css/jquery.ui.theme.css" rel="stylesheet" type="text/css" /> <link href="css/jquery-ui.css" rel="stylesheet" type="text/css" /> <link rel="stylesheet" type="text/css" href="css/style.css"> <link rel="stylesheet" type="text/css" media="screen" href="css/jquery.ui.datepicker.css"/> <script src="http://code.jquery.com/ui/1.9.2/jquery-ui.js"></script> </head> <script> var lastsel3; function FillGridOnEvent() { jQuery("#rowed6").jqGrid({ datatype: "local", height: 250, colNames:['ID Number','Last Sales','Name', 'Stock', 'Ship via','Notes'], colModel:[ {name:'id',index:'id', width:90, sorttype:"int", editable: true}, {name:'sdate',index:'sdate',width:90, editable:true, sorttype:"date",editoptions:{ dataInit: function(el) { setTimeout(function() { $(el).datepicker(); }, 200); }}}, {name:'name',index:'name', width:150,editable: true,editoptions{size:"20",maxlength:"30"}}, {name:'stock',index:'stock', width:60, editable: true,edittype:"checkbox",editoptions: {value:"Yes:No"}}, {name:'ship',index:'ship', width:90, editable: true,edittype:"select",editoptions: {value:"FE:FedEx;IN:InTime;TN:TNT;AR:ARAMEX"}}, {name:'note',index:'note', width:200, sortable:false,editable: true,edittype:"textarea", editoptions:{rows:"2",cols:"10"}}, ], onSelectRow: function(id){ if(id && id!==lastsel3){ jQuery('#rowed6').jqGrid('restoreRow',lastsel3); jQuery('#rowed6').jqGrid('editRow',id,true,pickdates); lastsel3=id; } }, editurl: "/MyServletNameHere", caption: "Date Picker Integration" }); var mydata3 = [ {id:"12345",name:"Desktop Computer",note:"note",stock:"Yes",ship:"FedEx", sdate:"2007-12-03"}, {id:"23456",name:"Laptop",note:"Long text ",stock:"Yes",ship:"InTime",sdate:"2007-12-03"}, {id:"34567",name:"LCD Monitor",note:"note3",stock:"Yes",ship:"TNT",sdate:"2007-12-03"}, {id:"45678",name:"Speakers",note:"note",stock:"No",ship:"ARAMEX",sdate:"2007-12-03"}, {id:"56789",name:"Laser Printer",note:"note2",stock:"Yes",ship:"FedEx",sdate:"2007-12-03"}, {id:"67890",name:"Play Station",note:"note3",stock:"No", ship:"FedEx",sdate:"2007-12-03"}, {id:"76543",name:"MobileTelephone", note:"note", stock:"Yes", ship:"ARAMEX", sdate:"2007-12-03"}, {id:"87654",name:"Server",note:"note2",stock:"Yes",ship:"TNT",sdate:"2007-12-03"}, {id:"98765",name:"Matrix Printer",note:"note3",stock:"No", ship:"FedEx",sdate:"2007-12-03"} ]; for(var i=0;i < mydata3.length;i++) jQuery("#rowed6").jqGrid('addRowData',mydata3[i].id,mydata3[i]); } function pickdates(id){ jQuery("#"+id+"_sdate","#rowed6").datepicker({dateFormat:"yy-mm-dd"}); } </script> <body> <body onload="FillGridOnEvent();"> <table id="rowed6"></table> </body> </html>
I would recommend you full rewrite your code. The most important problems: you need use <!DOCTYPE html ...>. It's very important because HTML without <!DOCTYPE> statement switch on quirks mode which is not supported by jQuery UI and jqGrid. you should use data: mydata3 instead of filling grid with addRowData in the loop you need call datepicker once (currently you call datepicker in both dataInit and oneditfunc parameter of editRow - pickdates) you need include every CSS and JavaScript file once. For example "js/jquery-ui-1.9.2.custom.css" should be enough. It should contain all CSS of jQuery UI (inclusive ui.datepicker.css). So you should remove lines with "css/ui.datepicker.css", "css/jquery-ui.css", css/jquery.ui.theme.css and "css/jquery.ui.datepicker.css" you should use jQuery.ready instead of usage onload. you should define all variables inside of some function (like inside of $(function () {/*here*/})). In the way you will have no global variables. you should be careful with encoding of special characters (like <) in case of usage inline code in HTML page. Try to validate the page on http://validator.w3.org/ for example and you will find the errors which I mean. I would strictly recommend you to use gridview: true to improve performance and use autoencode: true to be sure that jqGrid could display any text in the grid. UPDATED: The demo shows an example how the code could be modified. Below if the full HTML code. I used non-minimized version of all JavaScript files for better debugging. The productive code should use minimized version of the corresponding files: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>http://stackoverflow.com/q/14318014/315935</title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <link rel="stylesheet" type="text/css" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.9.2/themes/redmond/jquery-ui.css" /> <link rel="stylesheet" type="text/css" href="http://www.ok-soft-gmbh.com/jqGrid/jquery.jqGrid-4.3.2/css/ui.jqgrid.css" /> <style type="text/css"> html, body { font-size: 75%; } </style> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.js"></script> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.9.2/jquery-ui.js"></script> <script type="text/javascript" src="http://www.ok-soft-gmbh.com/jqGrid/jquery.jqGrid-4.4.1/js/i18n/grid.locale-en.js"></script> <script type="text/javascript"> $.jgrid.no_legacy_api = true; $.jgrid.useJSON = true; </script> <script type="text/javascript" src="http://www.ok-soft-gmbh.com/jqGrid/jquery.jqGrid-4.4.1/js/jquery.jqGrid.src.js"></script> <script type="text/javascript"> //<![CDATA[ /*global $ */ $(function () { "use strict"; var mydata = [ {id: "12345", name: "Desktop Computer", note: "note", stock: "Yes", ship: "FE", sdate: "2007-12-03"}, {id: "23456", name: "Laptop", note: "Long text", stock: "Yes", ship: "IN", sdate: "2007-12-03"}, {id: "34567", name: "LCD Monitor", note: "note3", stock: "Yes", ship: "TN", sdate: "2007-12-03"}, {id: "45678", name: "Speakers", note: "note", stock: "No", ship: "AR", sdate: "2007-12-03"}, {id: "56789", name: "Laser Printer", note: "note2", stock: "Yes", ship: "FE", sdate: "2007-12-03"}, {id: "67890", name: "Play Station", note: "note3", stock: "No", ship: "FE", sdate: "2007-12-03"}, {id: "76543", name: "MobileTelephone", note: "note", stock: "Yes", ship: "AR", sdate: "2007-12-03"}, {id: "87654", name: "Server", note: "note2", stock: "Yes", ship: "TN", sdate: "2007-12-03"}, {id: "98765", name: "Matrix Printer", note: "note3", stock: "No", ship: "FE", sdate: "2007-12-03"} ], $grid = $("#rowed6"), initDate = function (elem) { $(elem).datepicker({ dateFormat: "yy-mm-dd", //autoSize: true, defaultDate: new Date(2007, 11, 3), changeYear: true, changeMonth: true, showButtonPanel: true, showWeek: true, onSelect: function () { var $grid, grid; if (typeof (elem.id) === "string" && elem.id.substr(0, 3) === "gs_") { $grid = $(elem).closest("div.ui-jqgrid-hdiv") .next("div.ui-jqgrid-bdiv") .find("table.ui-jqgrid-btable:first"); if ($grid.length > 0) { grid = $grid[0]; if ($.isFunction(grid.triggerToolbar)) { grid.triggerToolbar(); } } } else { // to refresh the filter $(elem).trigger("change"); } } }); }, dateTemplate = {align: "center", sorttype: "date", width: 94, editrules: { date: true }, editoptions: { dataInit: initDate }, searchoptions: { sopt: ["eq", "ne", "lt", "le", "gt", "ge"], attr: { maxlength: 10, size: 11 }, // for searching toolbar maxlength: 10, size: 11, // for searching dialog dataInit: initDate }, formatter: "date", formatoptions: { srcformat: "ISO8601Short", newformat: "Y-m-d" }}, lastsel3; $grid.jqGrid({ datatype: "local", data: mydata, colNames: ["Last Sales", "Name", "Stock", "Ship via", "Notes"], colModel: [ { name: "sdate", template: dateTemplate }, { name: "name", width: 115, editoptions: {maxlength: "30"} }, { name: "stock", width: 70, align: "center", editable: true, formatter: "checkbox", edittype: "checkbox", editoptions: {value: "Yes:No", defaultValue: "Yes"}, stype: "select", searchoptions: { sopt: ["eq", "ne"], value: ":Any;true:Yes;false:No" } }, { name: "ship", width: 105, align: "center", editable: true, formatter: "select", edittype: "select", editoptions: { value: "FE:FedEx;IN:InTime;TN:TNT;AR:ARAMEX", defaultValue: "AR" }, stype: "select", searchoptions: { sopt: ["eq", "ne"], value: ":Any;FE:FedEx;IN:InTime;TN:TNT;AR:ARAMEX" } }, { name: "note", width: 60, sortable: false, editable: true, edittype: "textarea" } ], cmTemplate: {editable: true}, rowNum: 10, rowList: [5, 10, 100], pager: "#pager", gridview: true, rownumbers: true, autoencode: true, ignoreCase: false, viewrecords: true, sortname: "sdate", sortorder: "desc", height: "100%", onSelectRow: function (id) { if (id && id !== lastsel3) { $(this).jqGrid("restoreRow", lastsel3); $(this).jqGrid("editRow", id, true); lastsel3 = id; } }, editurl: "/MyServletNameHere", caption: "Date Picker Integration" }); $.extend($.jgrid.search, { recreateFilter: true, multipleSearch: true, multipleGroup: true, closeOnEscape: true, closeAfterSearch: true, overlay: 0, searchOnEnter: true }); $grid.jqGrid("navGrid", "#pager", {add: false, edit: false, del: false}); $grid.jqGrid("filterToolbar", {defaultSearch: "cn", stringResult: true}); }); //]]> </script> </head> <body> <table id="rowed6"><tr><td></td></tr></table> <div id="pager"></div> </body> </html>
I don't see any jquery-ui.js script included in your code. For example: <script src="http://code.jquery.com/ui/1.9.2/jquery-ui.js"></script> if you don't include that script you don't have jQuery-UI loaded and you can't use the datepicker widget.
Maybe try this: function pickdates(id){ jQuery("#rowed6 .hasDatepicker").datepicker('destroy'); jQuery("#"+id+"_sdate","#rowed6").datepicker({dateFormat:"yy-mm-dd"}); } Or by autotriggering click() handler adding click() at end: jQuery("#"+id+"_sdate","#rowed6").datepicker({dateFormat:"yy-mm-dd"}).click();