I have dispalyed a table in my web page i want to print it on the button click .My button is not working my code goes as follows.
<button id="button1">Print me</button>
<table id="printTable" style=" margin-bottom:50px; border-radius: 4px;" >
<thead>
<tr >
<th>Sl.No.</th>
<th>Description</th>
<th>Balance</th>
</tr>
</thead>
<tbody>
<script>
function printData()
{
var divToPrint=document.getElementById("printTable");
newWin= window.open("");
newWin.document.write(divToPrint.outerHTML);
newWin.print();
newWin.close();
}
$('#button1').on('click',function(){
printData();
})
</script>
CodePudding user response:
if you are not using jquery, do this :
function printData() {
var divToPrint = document.getElementById("printTable");
newWin = window.open("");
newWin.document.write(divToPrint.outerHTML);
newWin.print();
newWin.close();
}
const btn = document.getElementById("button");
btn.addEventListener('click', () => printData())
also you must close all tags (table, tbody..)
CodePudding user response:
Please use the below code. I have comment out the newWin.close() function so you will see the result.
<button id="button">Print me</button>
<table id="printTable" style=" margin-bottom:50px; border-radius: 4px;" >
<thead>
<tr >
<th>Sl.No.</th>
<th>Description</th>
<th>Balance</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
<script>
function printData()
{
var divToPrint=document.getElementById("printTable");
newWin= window.open("");
newWin.document.write(divToPrint.outerHTML);
newWin.document.close();
newWin.print();
//newWin.close();
}
document.querySelector("#button").addEventListener("click", function(){
printData();
});
</script>
CodePudding user response:
You don't have closing table tag. There is an opening tbody tag instead.