Suja Shyam
Suja Shyam

Reputation: 971

Passing div to jquery function and get its innerhtml

I have a function to print the content of a div. Let me share my aspx markup.

<div>
<div id="printarea" runat="server">
</div>
<asp:Button ID="btnPrint" runat="server" Text="Print Div" OnClick="btnPrint_Click" />

In the OnClick event innerhtml is set to the div printarea. The code is:

 protected void btnPrint_Click(object sender, EventArgs e)
    {

        string divText = GenerateInPatientBill();// "content you want to print";
        printarea.InnerHtml = divText;

        ScriptManager.RegisterStartupScript(this, Page.GetType(), "script", "PrintDiv(" + printarea.ClientID + ");", true);
    }

I need to pass the clientid of printarea div to the javascript function and get it printed. The javascript function used is

 function PrintDiv(printarea1) {
    alert($("#" + printarea1 + ""));
    var printContent = $("#" + printarea1 + "").html();
    alert(printContent);
    var popupWin = window.open('', '_blank', 'width=300,height=400,location=no,left=200px');
    popupWin.document.open();
    popupWin.document.write(printContent);
    popupWin.document.close();
    popupWin.focus();
    popupWin.print();
    popupWin.close();
}

Am getting javascript syntax error at line 2. Please help me on this.

Upvotes: 2

Views: 1969

Answers (2)

Techie
Techie

Reputation: 45124

Try this code below.

function printDiv(DivIdToPrint) 
{ 
  var divToPrint= document.getElementById('DivIdToPrint'); 
  var newWin=window.open('','Print-Window','width=100,height=100'); 
  newWin.document.open(); 
  newWin.document.write('<html><body onload="window.print()">'+divToPrint.innerHTML+'</body></html>'); 
  newWin.document.close(); 
  setTimeout(function(){newWin.close();},10); 
}

This JavaScript will open a new window with the content of the div, will print it and then will close that window. Last line, this is a must to set a timeout there, Otherwise in IE window will get closed before printing happens.

Else you can use a jQuery plugin

Upvotes: 1

Murali N
Murali N

Reputation: 3498

printContent wouldn't be available in newly opened window like so you are getting this error.To overcome this you should simple pass the div contents or markup to the newly opened window and then print

Upvotes: 0

Related Questions