Datepicker not working in html [closed] - javascript

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
This code is not working. I don't know what resource I need to add. I am following a link for Datepicker here: http://jsfiddle.net/rMhVz/1030/ And my code is down below. I really need to get it to work. I appreciate any help. Thanks in Advance.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery UI Datepicker - Default functionality</title>
<script src="http://ajax.aspnetcdn.com/ajax/jquery/jquery-1.9.0.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.9/jquery-ui.js"></script>
<link rel="stylesheet" href="http://ajax.microsoft.com/ajax/jquery.ui/1.8.7/themes/black-tie/jquery-ui.css"></link>
<link rel="stylesheet" href="/resources/demos/style.css"></link>
<style type="text/css">
.event > a {
background-color: gray !important;
background-image:none !important;
}
</style>
<script>
// hookup jquery ready function
$(document).ready(function () {
var Event = function(text, desc) {
this.text = text;
this.desc = desc;
};
var events = {};
events[new Date("07/06/2014")] = new Event("hello world test 1");
events[new Date("08/8/2014")] = new Event("hello world test 2");
events[new Date("09/26/2014")] = new Event("hello world test 3");
$("#dates").datepicker({
beforeShowDay: function(date) {
var event = events[date];
if (event) {
return [true, 'event', event.text];
}
else {
return [true, '', ''];
}
},
onSelect: function(dateText) {
var event = events[new Date(dateText)];
if (event) {
alert(event.text + "\n" + event.desc);
}
}
});
});
</script>
</head>
<body>
<div id="dates"></div>
</body>
</html>

Actually, I don't believe the script load order was the only problem. You're using incompatible versions of jQuery and jQuery UI. Your code breaks on a call to $.browser.msie. $.browser was removed in jQuery 1.9.
Source of error in jquery.ui:
html += buttonPanel + ($.browser.msie && parseInt($.browser.version,10) < 7 && !inst.inline ? '<iframe src="javascript:false;" class="ui-datepicker-cover" frameborder="0"></iframe>' : '');
Try using a more recent version of jQuery UI that is compatible with jQuery 1.9+.
See Uncaught TypeError: Cannot read property 'msie' of undefined - jQuery tools.
EDIT: For clarification, your script includes should be
<script src="http://ajax.aspnetcdn.com/ajax/jquery/jquery-1.9.0.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.9.1/jquery-ui.js"></script>
<link rel="stylesheet" href="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.9.1/themes/black-tie/jquery-ui.‌​css"></link>
Consider using jQuery 1.9.1, but it appears to work fine with 1.9.0.

You didn't include jQuery. Include it before any other js or jquery file and you should be good.

Include jQuery in the following order : jQuery - jQueryUI - jQueryUIcss.
Include css files using <link>.
<script src="http://ajax.aspnetcdn.com/ajax/jquery/jquery-1.9.0.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.9/jquery-ui.js"></script>
<link rel="stylesheet" href="http://ajax.microsoft.com/ajax/jquery.ui/1.8.7/themes/black-tie/jquery-ui.css"> </link>
Use $(document).ready(..) for your JS - so that all the execution happens after all the DOM elements are loaded.
<script>
$(document).ready(function(){
var Event = function(text, desc) {
this.text = text;
this.desc = desc;
};
var events = {};
events[new Date("07/06/2014")] = new Event("hello world test 1");
events[new Date("08/8/2014")] = new Event("hello world test 2");
events[new Date("09/26/2014")] = new Event("hello world test 3");
$("#dates").datepicker({
beforeShowDay: function(date) {
var event = events[date];
if (event) {
return [true, 'event', event.text];
}
else {
return [true, '', ''];
}
},
onSelect: function(dateText) {
var event = events[new Date(dateText)];
if (event) {
alert(event.text + "\n" + event.desc);
}
}
});
});
</script>

Just add jQuery before jQuery UI, use <link> instead of <script> for the css and use jQuery function from document.ready:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery UI Datepicker - Default functionality</title>
<script src="http://ajax.aspnetcdn.com/ajax/jquery/jquery-1.9.1.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.9.1/jquery-ui.js"></script>
<link rel="stylesheet" href="http://ajax.microsoft.com/ajax/jquery.ui/1.8.7/themes/black-tie/jquery-ui.css"></link>
<link rel="stylesheet" href="/resources/demos/style.css"></link>
<style type="text/css">
.event > a {
background-color: gray !important;
background-image:none !important;
}
</style>
<script>
// hookup jquery ready function
$(document).ready(function () {
var Event = function(text, desc) {
this.text = text;
this.desc = desc;
};
var events = {};
events[new Date("07/06/2014")] = new Event("hello world test 1");
events[new Date("08/8/2014")] = new Event("hello world test 2");
events[new Date("09/26/2014")] = new Event("hello world test 3");
$("#dates").datepicker({
beforeShowDay: function(date) {
var event = events[date];
if (event) {
return [true, 'event', event.text];
}
else {
return [true, '', ''];
}
},
onSelect: function(dateText) {
var event = events[new Date(dateText)];
if (event) {
alert(event.text + "\n" + event.desc);
}
}
});
});
</script>
</head>
<body>
<div id="dates"></div>
</body>
</html>

Related

Custom script working wrong in Blazor server side

I have Blazor Server side project with MudBlazor first, components working fine (I focus on text field).
Then I add Black Dashboard template (https://www.creative-tim.com/product/black-dashboard) into my project. And issue come.
Here's my _Host.cshtml
#page "/"
#namespace PPJ_Internal_Website_BlazorServer.Pages
#addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
#{
Layout = null;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>PPJ_Internal_Website_BlazorServer</title>
<base href="~/" />
#*<link rel="stylesheet" href="css/bootstrap/bootstrap.min.css" />
<link href="css/site.css" rel="stylesheet" />*#
<link href="PPJ_Internal_Website_BlazorServer.styles.css" rel="stylesheet" />
<link href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700&display=swap" rel="stylesheet" />
<link href="_content/MudBlazor/MudBlazor.min.css" rel="stylesheet" />
<link href="https://fonts.googleapis.com/css?family=Poppins:200,300,400,600,700,800" rel="stylesheet" />
<link href="https://use.fontawesome.com/releases/v5.0.6/css/all.css" rel="stylesheet">
<link href="assets/css/nucleo-icons.css" rel="stylesheet" />
<link href="assets/css/black-dashboard.css?v=1.0.0" rel="stylesheet" />
</head>
<body>
<component type="typeof(App)" render-mode="ServerPrerendered" />
<div id="blazor-error-ui">
<environment include="Staging,Production">
An error has occurred. This application may no longer respond until reloaded.
</environment>
<environment include="Development">
An unhandled exception has occurred. See browser dev tools for details.
</environment>
Reload
<a class="dismiss">🗙</a>
</div>
<script src="_content/MudBlazor/MudBlazor.min.js"></script>
<script src="assets/js/core/jquery.min.js"></script>
<script src="assets/js/core/popper.min.js"></script>
<script src="assets/js/core/bootstrap.min.js"></script>
<script src="assets/js/plugins/perfect-scrollbar.jquery.min.js"></script>
#*<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_KEY_HERE"></script>*#
<script src="assets/js/plugins/chartjs.min.js"></script>
<script src="assets/js/black-dashboard.min.js?v=1.0.0"></script>
#*<script src="js/customjs.js"></script>*#
<script src="https://cdn.trackjs.com/agent/v3/latest/t.js"></script>
<script src="_framework/blazor.server.js"></script>
<script>
$(document).ready(function () {
$().ready(function () {
$sidebar = $('.sidebar');
$navbar = $('.navbar');
$main_panel = $('.main-panel');
$full_page = $('.full-page');
$sidebar_responsive = $('body > .navbar-collapse');
sidebar_mini_active = true;
white_color = false;
window_width = $(window).width();
fixed_plugin_open = $('.sidebar .sidebar-wrapper .nav li.active a p').html();
$('.fixed-plugin a').click(function (event) {
if ($(this).hasClass('switch-trigger')) {
if (event.stopPropagation) {
event.stopPropagation();
} else if (window.event) {
window.event.cancelBubble = true;
}
}
});
$('.fixed-plugin .background-color span').click(function () {
$(this).siblings().removeClass('active');
$(this).addClass('active');
var new_color = $(this).data('color');
if ($sidebar.length != 0) {
$sidebar.attr('data', new_color);
}
if ($main_panel.length != 0) {
$main_panel.attr('data', new_color);
}
if ($full_page.length != 0) {
$full_page.attr('filter-color', new_color);
}
if ($sidebar_responsive.length != 0) {
$sidebar_responsive.attr('data', new_color);
}
});
$('.switch-sidebar-mini input').on("switchChange.bootstrapSwitch", function () {
var $btn = $(this);
if (sidebar_mini_active == true) {
$('body').removeClass('sidebar-mini');
sidebar_mini_active = false;
blackDashboard.showSidebarMessage('Sidebar mini deactivated...');
} else {
$('body').addClass('sidebar-mini');
sidebar_mini_active = true;
blackDashboard.showSidebarMessage('Sidebar mini activated...');
}
// we simulate the window Resize so the charts will get updated in realtime.
var simulateWindowResize = setInterval(function () {
window.dispatchEvent(new Event('resize'));
}, 180);
// we stop the simulation of Window Resize after the animations are completed
setTimeout(function () {
clearInterval(simulateWindowResize);
}, 1000);
});
$('.switch-change-color input').on("switchChange.bootstrapSwitch", function () {
var $btn = $(this);
if (white_color == true) {
$('body').addClass('change-background');
setTimeout(function () {
$('body').removeClass('change-background');
$('body').removeClass('white-content');
}, 900);
white_color = false;
} else {
$('body').addClass('change-background');
setTimeout(function () {
$('body').removeClass('change-background');
$('body').addClass('white-content');
}, 900);
white_color = true;
}
});
$('.light-badge').click(function () {
$('body').addClass('white-content');
});
$('.dark-badge').click(function () {
$('body').removeClass('white-content');
});
});
});
</script>
<script>
$(document).ready(function () {
// Javascript method's body can be found in assets/js/demos.js
demo.initDashboardPageCharts();
});
</script>
<script src="https://cdn.trackjs.com/agent/v3/latest/t.js"></script>
<script>
window.TrackJS &&
TrackJS.install({
token: "ee6fab19c5a04ac1a32a645abde4613a",
application: "black-dashboard-free"
});
</script>
</body>
</html>
When I remove <script src="_framework/blazor.server.js"></script>, my custom script tag is working fine, I can change theme, sidbar background but MudBlazor text field working not good.
When I add <script src="_framework/blazor.server.js"></script>, Mud component working good, but custom scripts don't work, I can't change sidebar background or theme.
How can I fix this?
Blazor doesn’t interact with JavaScript the same way that server-side rendered pages do. Components only redraw when Blazor can tell the state has changed (and has various automatic and manual ways of invoking this). That is why when Blazor server js is left out it works and doesn’t when included.
You either need to invoke those JavaScript functions manually by wiring up your own methods that invoke them, write your own Blazor code that does it for you, or find a library with parity functionality.

How to save a list of "divs" to sessionStorage and display them when the user reloads the page?

I have an HTML page as follows:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="styles.css" type="text/css">
<title>Test</title>
</head>
<body>
<div>
<p>Hello World!</p>
</div>
</body>
</html>
Then I have a JS file that listens for clicks of the enter key, and if the user clicks enter if adds another div.
//the event handler function
function captureEnterPress(event) {
if (event.key === "Enter" || event.keyCode === 13) {
event.preventDefault();
createNewDiv();
}
}
//creates the div
function createNewDiv() {
var body = document.body;
var div = document.createElement("div");
var p = document.createElement("p");
var labelText = document.createTextNode("Hello World!");
p.appendChild(labelText);
div.appendChile(p);
body.appendChild(div);
}
onload = () => {
document.documentElement.addEventListener("keyup", captureEnterPress);
}
I am trying to have the number of divs saved, so when the user reloads the page it shows the same amount of divs like he had before.
What I tried
I tried saving an array of all the divs to sessionStorage as follows:
var myStorage = window.sessionStorage;
var elementsArray = [];
//the event handler function
function captureEnterPress(event) {
if (event.key === "Enter" || event.keyCode === 13) {
event.preventDefault();
createNewDiv();
}
}
//creates the div
function createNewDiv() {
var body = document.body;
var div = document.createElement("div");
var p = document.createElement("p");
var labelText = document.createTextNode("Hello World!");
p.appendChild(labelText);
div.appendChile(p);
body.appendChild(div);
elementsArray[elementsArray.length] = div;
myStorage.setItem("storedPage", JSON.stringify(elementsArray));
}
onload = () => {
var storedPage = JSON.parse(myStorage.getItem("storedPage"));
if(storedPage){
event.preventDefault();
for(var i = 0; i < storedPage.length; i++){
document.body.appendChild(storedPage[i]);
console.log(storedPage)
}
}
document.documentElement.addEventListener("keyup", captureEnterPress);
}
I just logged it to the console to see what the values are, but they are empty. So I tried storing the div.innerHTML instead, but then if I try to append it to the document I get and error that it's a String and not a node.
I am out of ideas, and I am pretty new to the whole state storing concept in front-end development I would appreciate if somebody could tell me what is the right way to do it.
Thanks!
Not tested, but enough to illustrate
function createNewDiv() {
// create html content
const div = `<div><p>Hello World!</p></div>`;
// concat with body
document.body.innerHTML += div;
// save in array
elementsArray[elementsArray.length] = div;
// save in storage
myStorage.setItem("storedPage", JSON.stringify(elementsArray));
}
onload = () => {
var storedPage = JSON.parse(myStorage.getItem("storedPage"));
if(storedPage){
event.preventDefault();
// get stored content array and join by empty '' and add into body
document.body.innerHTML = storedPage.join('');
}
document.documentElement.addEventListener("keyup", captureEnterPress);
}
The problem I see in this code is that JSON.stringify is not able to convert DOM elements. Article on how to do this.
However, the better way is to save the innerHTML of some container, and then restore it.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="styles.css" type="text/css">
<title>Test</title>
</head>
<body>
<div id="div-container">
<div>
<p>Hello World!</p>
</div>
</div>
</body>
</html>
JS:
var myStorage = window.sessionStorage;
var elementsArray = [];
//the event handler function
function captureEnterPress(event) {
if (event.key === "Enter" || event.keyCode === 13) {
event.preventDefault();
createNewDiv();
}
}
//creates the div
function createNewDiv() {
var divContainer = document.getElementById("div-container");
const div = "<div><p>Hello World!</p></div>";
divContainer.innerHTML += div;
console.log(divContainer.innerHTML);
myStorage.setItem("storedPage", divContainer.innerHTML);
}
onload = () => {
var storedPage = myStorage.getItem("storedPage");
if(storedPage){
event.preventDefault();
var divContainer = document.getElementById("div-container");
divContainer.innerHTML = storedPage;
}
document.documentElement.addEventListener("keyup", captureEnterPress);
}
JSFiddle: https://jsfiddle.net/wLgh1ef8/1/
Edit:
You always can see the content of sessionStorage using DevTools
F12 -> Application tab -> Session Storage

Right click context menu with Ext.form.field.HtmlEditor

Problem description
I have prepared this index.html, which creates a simple Ext.form.field.HtmlEditor. I want to have a right-click-context-menu, which is capable of doing something with words that were marked by the user:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="/ext-5.1.1/build/ext-all-debug.js"></script>
<link id="theme1" rel="stylesheet" type="text/css" href="/ext-5.1.1/build/packages/ext-theme-neptune/build/resources/ext-theme-neptune-all.css">
<script type="text/javascript" src="/ext-5.1.1/build/packages/ext-theme-neptune/build/ext-theme-neptune.js"></script>
<script type ="text/javascript">
Ext.onReady( function(){
var html_editor = Ext.create('Ext.form.HtmlEditor', {
renderTo: Ext.getBody()
});
});
</script>
</head>
<body></body>
What i have done so far:
I have tried to implement listeners and a contextmenu, but it doesnt show the menu when right-clicking, so at the end of the day my index.html looked like:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="/ext-5.1.1/build/ext-all-debug.js"></script>
<link id="theme1" rel="stylesheet" type="text/css" href="/ext-5.1.1/build/packages/ext-theme-neptune/build/resources/ext-theme-neptune-all.css">
<script type="text/javascript" src="/ext-5.1.1/build/packages/ext-theme-neptune/build/ext-theme-neptune.js"></script>
<script type ="text/javascript">
Ext.onReady( function(){
var html_editor_right_click_menu_action_1 = Ext.create('Ext.Action', {
text: 'html_editor_right_click_menu_action_1',
handler: function(widget, event) {
console.log("html_editor_right_click_menu_action_1 clicked!");
}
});
var html_editor_right_click_menu = Ext.create('Ext.menu.Menu', {
items: [html_editor_right_click_menu_action_1]
});
var html_editor = Ext.create('Ext.form.HtmlEditor', {
renderTo: Ext.getBody(),
viewConfig: {
listeners: {
containercontextmenu: function(view, e, eOpts) {
console.log("containercontextmenu listener");
}
}
}
});
});
</script>
</head>
<body></body>
Unfortunately, neither a console.log() for the right-click nor a right-click-menu is showing up.
Can someone point me in the right direction?
EDIT: (progress made)
I made a context menu appear using this code in index.html (the index.html is runnable for itself, if someone wants to copy&paste it), but i can't get rid of the browsers-context-menu showing inside the html_editor:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="/ext-5.1.1/build/ext-all-debug.js"></script>
<link id="theme1" rel="stylesheet" type="text/css" href="/ext-5.1.1/build/packages/ext-theme-neptune/build/resources/ext-theme-neptune-all.css">
<script type="text/javascript" src="/ext-5.1.1/build/packages/ext-theme-neptune/build/ext-theme-neptune.js"></script>
<script type ="text/javascript">
Ext.onReady( function(){
var html_editor_right_click_menu_action_1 = Ext.create('Ext.Action', {
text: 'html_editor_right_click_menu_action_1',
handler: function(widget, event) {
console.log("html_editor_right_click_menu_action_1 clicked!");
}
});
var html_editor_right_click_menu = Ext.create('Ext.menu.Menu', {
items: [html_editor_right_click_menu_action_1]
});
var html_editor = Ext.create('Ext.form.HtmlEditor', {
renderTo: Ext.getBody()
});
html_editor.getEl().addListener('click',
html_editor_click_handler,
html_editor);
function html_editor_click_handler(btn, e, eOpts){
var clicked_button = btn.button;
var click_x_pos = btn.pageX;
var click_y_pos = btn.pageY;
console.log(clicked_button + " " + click_x_pos + " " + click_y_pos);
if(clicked_button == 2){
html_editor_right_click_menu.showAt(click_x_pos,click_y_pos);
}
}
});
</script>
</head>
<body></body>
How to stop the browser-context-menu from appearing above the extjs5-context-menu?
To prevent the default context menu from showing up, call event.preventDefault()
However, there is an extra wrinkle in this case. The HTMLEditor creates an iframe which is used to do the editing.
You have to then set a contextmenu listener on the body of the iframe, after it has loaded. See https://fiddle.sencha.com/#fiddle/ncn
You should not do what you were doing (handling the click and checking which button was clicked) because there are other ways to show the context menu. On the Mac, you can ctrl+click, on Windows you can use the context menu key on the keyboard.
var html_editor_right_click_menu_action_1 = Ext.create('Ext.Action', {
text: 'html_editor_right_click_menu_action_1',
handler: function(widget, event) {
console.log("html_editor_right_click_menu_action_1 clicked!");
}
});
var html_editor_right_click_menu = Ext.create('Ext.menu.Menu', {
items: [html_editor_right_click_menu_action_1]
});
var html_editor = Ext.create('Ext.form.HtmlEditor', {
renderTo: Ext.getBody()
});
// Find the iframe and wait until it's loaded
var iframe = html_editor.getEl().down('iframe', true);
iframe.addEventListener('load', function() {
// It's loaded, now set the context menu listener
var body = iframe.contentWindow.document.body;
body.addEventListener('contextmenu', html_editor_click_handler);
});
function html_editor_click_handler(e, iframe) {
// Prevents the default context menu
e.preventDefault();
var click_x_pos = e.pageX;
var click_y_pos = e.pageY;
console.log("Context click " + click_x_pos + " " + click_y_pos);
html_editor_right_click_menu.showAt(click_x_pos, click_y_pos);
}

Implemeting Create and Delete function properly using javascript

I am able to create a div using javascript. However, not able to remove that div that I created previously. Only after post-back, I can remove that div. Actually after creating div, script cannot find that div because page did not loaded again.
What I want to do is to create a page that I am able to add an item and remove that item.
Add script works fine.
Remover script:
<script type="text/javascript">
$(function () {
$('.remove ,.shop-button-large, .shop-button-add').click(function () {
var itemToDelete = $(this).attr("data-id");
if (itemToDelete != '') {
$.post("/ShoppingBox/RemoveFromBox", { "id": itemToDelete },
function (data) {
$("#boxItem-" + itemToDelete + "-" + data.ItemCount).fadeOut(300);
});
}
});
});
</script>
The click handler for the remove was done before the DOM node was rendered. It needs to be insider the $(function() { ... }
http://plnkr.co/edit/IhtyH6ampodXICPBv6Fq?p=preview
<!DOCTYPE html>
<html>
<head>
<script data-require="jquery#2.1.3" data-semver="2.1.3" src="http://code.jquery.com/jquery-2.1.3.min.js"></script>
<script>
$(function() {
$("#create").click(function() {
var createDiv = document.createElement("div");
createDiv.id = "myDiv";
createDiv.style.margin = "0 auto";
createDiv.style.width = "600px";
createDiv.style.height = "600px";
createDiv.style.backgroundColor = "red";
document.getElementById("myBody").appendChild(createDiv);
});
$("#remove").click(function() {
console.log('remove', $("#myDiv"));
$("#myDiv").fadeOut(300);
});
});
</script>
</head>
<body id="myBody">
Create
Remove
</body>
</html>
In order to clarify, I have prepared a simple code:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script src="js/jquery-2.1.3.intellisense.js"></script>
<script src="js/jquery-2.1.3.min.js"></script>
<script src="js/jquery-2.1.3.js"></script>
<script src="js/jquery-ui.js"></script>
<script>
$(function () {
$("#create").click(function () {
var createDiv = document.createElement("div");
createDiv.id ="myDiv";
createDiv.style.margin = "0 auto";
createDiv.style.width = "600px";
createDiv.style.height = "600px";
createDiv.style.backgroundColor = "red";
document.getElementById("myBody").appendChild(createDiv);
});
});
$("#remove").click(function () {
$("#myDiv").fadeOut(300);
});
</script>
<title></title>
</head>
<body id="myBody">
Create
Remove
</body>
</html>

Print content of jquery dialog to a printer

I have the following jQueryUI dialog. How can I print the content of the dialog? The content could be any HTML such as a table, image, etc. There were several earlier answers to this question,however, they appear to be out of date.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>jQuery UI Dialog</title>
<script src="http://code.jquery.com/jquery-latest.js" type="text/javascript"></script>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.1/themes/base/jquery-ui.css" />
<script src="http://code.jquery.com/ui/1.10.1/jquery-ui.js"></script>
<script>
$(function() {
$("#openDialog").click(function(){$("#myDialog").dialog('open')});
$( "#myDialog" ).dialog({
modal: true,
autoOpen : false,
buttons: {Ok: function() {alert('print');}}
});
});
</script>
</head>
<body>
<button id="openDialog">Click</button>
<div id="myDialog" title="My Dialog">
<p>Print this text!</p>
<img alt="And print this image" src="myImg.png">
</div>
</body>
</html>
I developed my own plugin with code is below, and a live example is located at http://jsfiddle.net/fyu4P/embedded/result/.
On FF 26.0, it works, however, after printing a couple of times, FF asks the user if popups should be disabled which I wish not to happen. Also, it doesn't work with older IE, and likely other browsers. Don't worry, when printing, you still need to click the operating system print dialog, so you won't waste any paper! I've asked https://codereview.stackexchange.com/questions/39235/critique-of-jquery-plugin-which-will-print-to-a-printer-an-element-or-a-jqueryui for any recommendations.
Actual Plugin:
/*
* jQuery printIt
* Print's the selected elements to the printer
* Copyright Michael Reed, 2014
* Dual licensed under the MIT and GPL licenses.
*/
(function($){
var defaults = {
elems :null, //Element to print HTML
copy_css :false,//Copy CSS from original element
external_css :null //New external css file to apply
};
var methods = {
init : function (options) {
var settings = $.extend({}, defaults, options)
elems=$(settings.elems);
return this.each(function () {
$(this).click(function(e) {
var iframe = document.createElement('iframe');
document.body.appendChild(iframe);
$(iframe).load(function(){
elems.each(function(){
iframe.contentWindow.document.body.appendChild(this.cloneNode(true));
});
if(settings.copy_css) {
var arrStyleSheets = document.getElementsByTagName("link");
for (var i = 0; i < arrStyleSheets.length; i++){
iframe.contentWindow.document.head.appendChild(arrStyleSheets[i].cloneNode(true));
}
var arrStyle = document.getElementsByTagName("style");
for (var i = 0; i < arrStyle.length; i++){
iframe.contentWindow.document.head.appendChild(arrStyle[i].cloneNode(true));
}
}
if(settings.external_css) {
var style = document.createElement("link")
style.rel = 'stylesheet';
style.type = 'text/css';
style.href = settings.external_css;
iframe.contentWindow.document.head.appendChild(style);
}
var script = document.createElement('script');
script.type = 'text/javascript';
script.text = 'window.print();';
iframe.contentWindow.document.head.appendChild(script);
$(iframe).hide();
});
});
});
},
destroy : function () {
//Anything else I should do here?
delete settings;
return this.each(function () {});
}
};
$.fn.printIt = function(method) {
if (methods[method]) {
return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
} else if (typeof method === 'object' || ! method) {
return methods.init.apply(this, arguments);
} else {
$.error('Method ' + method + ' does not exist on jQuery.printIt');
}
};
}(jQuery)
);
To configure:
$(function () {
$("#openDialog").click(function () {
$("#myDialog").dialog('open')
});
$("#myDialog").dialog({
modal: true,
autoOpen: false
});
$('#printIt').printIt({
elems: $("#myDialog"),
copy_css: true,
external_css: 'test2.css'
});
});
This will add a printable area, and puts modal html into it.
$(function () {
$("#openDialog").click(function () {
$("#myDialog").dialog('open')
});
$("#myDialog").dialog({
modal: true,
autoOpen: false,
buttons: {
Ok: function (e) {
$('#divToPrint').html($(this)[0].innerHTML).printArea();
}
}
});
});
You need to create a new <div id="divToPrint"></div> if you want to not display the new div, just use style="display: none;"
Then when you press CTRL+P it will print what you created...
Try like below.....and call your div id. You should be good to go.
buttons: {
"Print": function() {
$("#dialog").printArea();
},
"Close": function() {
$(this).dialog("close");
}
}

Categories

Resources