1

I have this codes in my projects to open a new window to show and then, print the result table from my first window:

$('a.print_btn').click(function(e) {
    var elementId = $(this).attr('id');
    var elementToPrint = $("#report_" + elementId).html();
    var printWin = window.open("print.php?id="+elementId, "Print");
    $(printWin.document.body).html(elementToPrint);
}); 

In this code, #report_elementId points to a fieldset that contains my table information. If I use the code below I can see all table contents:

alert(elementToPrint);

So everything is ok so far. But the last line of code does not work and anything don't write in printWin window. I don't know why :(

I used Write Content To New Window with JQuery for it, but it does not work for me. Help me please.

By the way, I need to write contents to a certain div (id="myDiv"). How can I do it?

Community
  • 1
  • 1
Mohammad Saberi
  • 12,864
  • 27
  • 75
  • 127

2 Answers2

2

Try this:

  var printWin = window.open("print.php?id="+elementId, "Print");
  $(printWin.document).ready( function() {
     $('div#myDiv').html(elementToPrint); 
  }

I assume print.php?id=[something] does work, ie not ending in a 500 or a 404 error...

As I'm uncertain in what context the ready callback is executed let's try to be more explicit:

  var printWin = window.open("print.php?id="+elementId, "Print");
  $(printWin.document).ready( function() {
     $(printWin.document).find('div#myDiv').html(elementToPrint); 
  }
rene
  • 41,474
  • 78
  • 114
  • 152
  • rene, `$('myDiv').html(elementToPrint);` does not work for me :( I don't know why. If I alert `elementToPrint` I can see all html contents, but I don't know why it can not be written – Mohammad Saberi Jan 01 '12 at 06:13
  • It seems that I don't have any access to `$('myDiv')`. I tried `$('myDiv').css('background-color','#333');` too. But anything did not happen. – Mohammad Saberi Jan 01 '12 at 06:16
  • @Mohammad I added a second example to make sure selection runs the right context – rene Jan 01 '12 at 11:24
  • but this line `$(printWin.document).find('div#myDiv').html(elementToPrint); ` didn't work for me-@rene – ubm Feb 14 '17 at 06:10
  • @ubm ask a new question where you follow the guidance in [mcve] to make sure we can see what is different between your case and this one. It could be a security policy, a jquery error, html markup that is wrong etc. There is barely enough info your comment to diagnose what could be wrong. – rene Feb 14 '17 at 09:02
  • @rene I have no permission to ask questions,thank you for your response – ubm Feb 14 '17 at 09:12
0

Try

printWin.body.innerHTML = elementToPrint;
document.getElementById('myDiv').innerHTML = elementToPrint;
Dion
  • 3,145
  • 20
  • 37