Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery for print function not working in asp.net

I have written the following script to print a document:

<script type="text/javascript">
    function print() {
        window.print();
    }
    $(".printdoc").click(function () {
        print();
    });
 </script>

and I am invoking the above script by an <asp:button../> as follows:

<asp:Button ID="btnPrint" runat="server" Text="Print" CssClass="printdoc"/>

Every time I click on the button it loads the page again but the query doesn't seem to work.

When I checked the resources , I found the following console error:

Uncaught ReferenceError: $ is not defined

like image 664
Kinchit Dalwani Avatar asked Dec 08 '25 19:12

Kinchit Dalwani


1 Answers

print may collide with the built in print function. So let's call it printPage.

<script type="text/javascript">
    function printPage() {
        window.print();
    }
 </script>

In additional to Rahul's solution for referencing jQuery, by default asp:Button will postback to the server when clicked. So switch to a regular button.

<button type="button" onclick="printPage()" runat="server">Print</button>

You can leave the runat attribute off if you want, it's only necessary if you want to refer to it from the code behind.


If you really wanna use the asp:Button, you can do this:

<asp:Button ID="btnPrint" runat="server" Text="Print" OnClientClick="printPage(); return false;"/>

The return false; will prevent the postback. But I don't see much point in using asp:Button for client side things.

like image 101
mason Avatar answered Dec 11 '25 10:12

mason



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!