Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print a div content using Jquery

I want to print the content of a div using jQuery. This question is already asked in SO, but I can't find the correct (working) answer.

This is is my HTML:

<div id='printarea'>     <p>This is a sample text for printing purpose.</p>     <input type='button' id='btn' value='Print'> </div> <p>Do not print.</p> 

Here I want to print the content of the div printarea.

I tried this:

$("#btn").click(function () {     $("#printarea").print(); }); 

But it gives a console error when the button is clicked:

Uncaught TypeError: $(...).print is not a function

But when I am trying to print the entire page using

window.print(); 

it is working. But I only want to print the content of a particular div. I saw the answer $("#printarea").print(); in many places , but this is not working.

like image 823
Deepu Sasidharan Avatar asked Nov 16 '15 10:11

Deepu Sasidharan


People also ask

How do I print something in jQuery?

jQuery Code:$('#sudo). click(function(){ window. print(); return false; });

How do you print an element in JavaScript?

To print the content of div in JavaScript, first store the content of div in a JavaScript variable and then the print button is clicked. The contents of the HTML div element to be extracted.

How do you print HTML content on click of a button but not the page?

One of those solutions are: I can keep this HTML content in a div and make it display: to print, but display: none to screen. All other elements on the webpage can be made to display: none for print and display: for the screen. And then call to print.


1 Answers

Some jQuery research has failed, so I moved to JavaScript (thanks for your suggestion Anders).

And it is working well...

HTML

<div id='DivIdToPrint'>     <p>This is a sample text for printing purpose.</p> </div> <p>Do not print.</p> <input type='button' id='btn' value='Print' onclick='printDiv();'> 

JavaScript

function printDiv()  {    var divToPrint=document.getElementById('DivIdToPrint');    var newWin=window.open('','Print-Window');    newWin.document.open();    newWin.document.write('<html><body onload="window.print()">'+divToPrint.innerHTML+'</body></html>');    newWin.document.close();    setTimeout(function(){newWin.close();},10);  } 
like image 187
Deepu Sasidharan Avatar answered Sep 22 '22 11:09

Deepu Sasidharan