Javascript – Print html through JavaScript / jQuery

htmljavascriptjqueryjquery-ui

I wish to print a document by passing custom html code.

The non-working code I have written :

function Clickheretoprint()
{
  var disp_setting="toolbar=yes,location=no,directories=yes,menubar=yes,"; 
      disp_setting+="scrollbars=yes,width=780, height=780, left=100, top=25"; 
  var content_vlue = document.getElementById("result_tbl").innerHTML; 

  var docprint=window.open("","",disp_setting); 
  docprint.document.open(); 
  docprint.document.write('<html><head><title>Ashley Mattresses</title>'); 
  docprint.document.write('</head><body onLoad="self.print()"><center>');          
  docprint.document.write('<TABLE width="100%" cellpadding=10 align=center  valign="top"><TR valign="top"><TD width = "33%" valign="top">col1</TD><TD width = "33%" valign="top">col2</TD><TD width = "33%" valign="top">col3</TD></TR></TABLE>');     
  docprint.document.write('</center></body></html>'); 
  docprint.document.close(); 
  docprint.focus(); 
  docprint.close();
}

This is the method I called on href of an anchor tag, but the not getting the work done:

<a href="javascript:Clickheretoprint()">

I am a beginner to JavaScript/jQuery coding.

Best Solution

You are on the right track. Assuming result_tbl is the ID of element you like to print as-is, first wrap the element with a <div> tag e.g.:

<div>
    <table id="result_tbl">
        .....
    </table>
</div>

Then have such code:

var docprint=window.open("about:blank", "_blank", disp_setting); 
var oTable = document.getElementById("result_tbl");
docprint.document.open(); 
docprint.document.write('<html><head><title>Ashley Mattresses</title>'); 
docprint.document.write('</head><body><center>');
docprint.document.write(oTable.parentNode.innerHTML);
docprint.document.write('</center></body></html>'); 
docprint.document.close(); 
docprint.print();
docprint.close();

Live test case.

Working fine for me under Chrome 18:

print is working