Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

text of input field is not printing while print using window.print()

I have following html layout:

Please fill up this form carefully:
<input type="button" onclick="printDiv('print'); return false;" value="Print" />
<div id="print">
  <form action="" method="post">
     <input type="text" name="user_name" value="" />
     <input type="text" name="address" value="" />
     <input type="text" name="date" value="14-06-2015" />
     <input type="submit" value="SUBMIT" />
  </form>
</div>

and the printDiv('print') function in the head section of that html page:

function printDiv(divName) {
  var printContents = document.getElementById(divName).innerHTML;
  var originalContents = document.body.innerHTML;
  document.body.innerHTML = printContents;
  window.print();
  document.body.innerHTML = originalContents;
}

but while printing the form after filled-up, it is not showing the text of input fields that an user entered in the input box. but the predefined text (here the date field) of the input field of the same form is printing as usual.

How can I rewrite the javascript function so that it will print the text of input fields aslo?

like image 668
Abdullah Mamun-Ur- Rashid Avatar asked Jun 14 '15 04:06

Abdullah Mamun-Ur- Rashid


2 Answers

That's because innerHTML does not reflect changes by the user in input fields. See innerHTML example: With user input it doesn´t work, why?. A better solution is to use a CSS stylesheet to control the printable content.

@media print {
    body {display:none};
    #print {display: block};
}

I am on a phone so I can't test it, you may need to update your HTML and CSS so that you don't have nested conflicting display rules

like image 136
Juan Mendes Avatar answered Nov 10 '22 02:11

Juan Mendes


Some years later, but... i have an idea to solve this that worked for me. It's very simple:

$('form#myId input').bind("change", function() {
    var val = $(this).val();
    $(this).attr('value',val);
});

We only collect the input value and, in the change event, replace it with the same value that we just entered using attr(). When replacing, it's already recorded in the DOM and will be loaded when we trying to print. I don't think that more explanation is needed, it's very simple.

Regards.

like image 34
Drewkenobi Avatar answered Nov 10 '22 02:11

Drewkenobi