To print the form inside an Ngb popup modal with Bootstrap classes using JavaScript, you can follow these steps:
- Create a printForm JavaScript function:
function printForm() {
// Get the modal element
var modal = document.getElementById('myModal');
// Clone the form inside the modal
var form = modal.querySelector('form').cloneNode(true);
// Create a new window
var printWindow = window.open('', '_blank');
// Write the form HTML to the new window
printWindow.document.write('<html><head><title>Print Form</title>');
printWindow.document.write('<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">');
printWindow.document.write('</head><body><div class="container">');
printWindow.document.write(form.outerHTML);
printWindow.document.write('</div></body></html>');
// Close the document for writing
printWindow.document.close();
// Focus and print the new window
printWindow.focus();
printWindow.print();
// Close the new window after printing
printWindow.close();
}
- In your HTML, create a button or link that triggers the
printForm function:
<button onclick="printForm()">Print Form</button>
- Use the Ngb modal component from Bootstrap to create a modal with the form inside:
<!-- Button to open the modal -->
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#myModal">
Open Modal
</button>
<!-- The modal -->
<div class="modal" id="myModal">
<div class="modal-dialog">
<div class="modal-content">
<!-- Modal body -->
<div class="modal-body">
<form>
<!-- Your form elements go here -->
</form>
</div>
<!-- Modal footer -->
<div class="modal-footer">
<button type="button" class="btn btn-primary" onclick="printForm()">Print</button>
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
Make sure you have included the necessary Bootstrap and Ngb dependencies in your HTML head section:
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
When the "Print" button is clicked, the printForm function will clone the form inside the modal, create a new window, write the form HTML to the new window, and trigger the print dialog.