He mostrado una tabla en mi página web. Quiero imprimirla al hacer clic en el botón. Mi botón no funciona. Mi código es el siguiente.
<button id="button1">Print me</button> <table id="printTable" class="display responsive-table " 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>si no está usando jquery, haga esto:
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())también debe cerrar todas las etiquetas (table, tbody..)
Utilice el siguiente código. He comentado la función newWin.close() para que veas el resultado.
<button id="button">Print me</button> <table id="printTable" class="display responsive-table " 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>No tienes la etiqueta de la tabla de cierre. En su lugar, hay una etiqueta de apertura tbody.