javahtmlprinting

Print only html table using javascript


I have the following basic html table with a Java function to print only the table content However the Print button does nothing when clicked,I figure probably the java coding is the issue, however it is not working could I get a third pair of eyes to assist please

<html>
<body>

<table border="1" cellpadding="3" id="printTable">
    <tbody><tr>
        <th>First Name</th>
        <th>Last Name</th>      
        <th>Points</th>
    </tr>
    <tr>
        <td>Jill</td>
        <td>Smith</td>      
        <td>50</td>
    </tr>
    <tr>
        <td>Eve</td>
        <td>Jackson</td>        
        <td>94</td>
    </tr>
    <tr>
        <td>John</td>
        <td>Doe</td>        
        <td>80</td>
    </tr>
    <tr>
        <td>Adam</td>
        <td>Johnson</td>        
        <td>67</td>
    </tr>
</tbody></table>

<br />
<br />

<button>Print me</button>

<script>
function printData()
{
   var divToPrint=document.getElementById("printTable");
   newWin= window.open("");
   newWin.document.write(divToPrint.outerHTML);
   newWin.print();
   newWin.close();
}

$('button').on('click',function(){
printData();
})
</script>
</body>
</html>

Solution

  • The call to the javascript function is not correct. When you're using the '$' symbol it means that you're using JQuery. You have 2 options:

    1 - Include the jquery library to your page:

    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.4.3/jquery.min.js"></script>
    

    2 - Call the javascript function directly on the button on the 'onclick' event. This is the best option in your case:

    <button onclick="printData()">Print me</button>