Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
694 views
in Technique[技术] by (71.8m points)

javascript - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...