0

I am trying to add a print button for a form on the website that I maintain for a voluntary organization in Scotland. I would stress that I am not an expert in either HTML or Javascript but do my best.

The answer given by Murali to question 20101409 on 20th November 2013 looks as if it should work but does not. I suspect that I not named or defined something correctly.

My test webpage is: http://clanmacthomas.co.uk/Pages/TestCalculations.aspx

Community
  • 1
  • 1
  • the "printDiv" function is undefined and the area where it looks like you're trying to define it is a mess. – user13286 Apr 21 '14 at 17:18
  • Please read [Something on my web site doesn't work. Can I just paste a link to it?](http://meta.stackexchange.com/questions/125997/something-on-my-web-site-doesnt-work-can-i-just-paste-a-link-to-it). Questions that depend on external resources to be understood become useless when the external resource goes away or is fixed. Create an [SSCCE](http://www.sscce.org/) instead. – Quentin Apr 21 '14 at 17:53

2 Answers2

1

I strongly discourage the use <a href="javascript:..something.."> for any purpose, and especially the use of links to perform actions, preferring buttons instead.

If you have

<div>stuff</div>
<div>more stuff</div>
<input type="button" id="print" value="Print this page">

You can later attach a handler to it by using

<script>
document.getElementById("print").addEventListener("click", function() {
    if (window.print) window.print();
});
</script>

If you are likely to want a print button on more than that one page, put that code in a .js file

/* printer.js */
document.getElementById("print").addEventListener("click", function() {
    if (window.print) window.print();
});

There are nicer ways to do it if you are using jQuery, but you didn't mention that so I'm avoiding it.

You may want to read the SO question "Correct usage of addEventListener() / attachEvent()" since older versions of Internet Explorer use attachEvent instead of addEventListener.

Community
  • 1
  • 1
Stephen P
  • 14,422
  • 2
  • 43
  • 67
0

To add a link that will open the print dialog on a webpage, include this link somewhere:

<a href="javascript:if(window.print)window.print()">Print</a>
qJake
  • 16,821
  • 17
  • 83
  • 135
  • please don't encourage inline scripting. your answer is valid, but highly abused by n00bs. and i don't want to sound discouraging, rather, encouraging. its a good answer – albert Apr 21 '14 at 18:18