Conceal blank fields in print layout using JavaScript

I need help with a form that needs to be printed, but I want to exclude any blank fields from the print view when using the JavaScript window.print(); function and its print window.

Is there a possibility to implement logic to handle this situation before printing? Any suggestions or solutions?

Answer №1

To alter the class based on whether a field is empty or not, you can utilize CSS @media in conjunction with JavaScript. Below is an example of how this can be achieved.

var fields = document.getElementsByClassName("field");
for(var i=0; i < fields.length; i++){
    fields[i].addEventListener('keyup', function() {
    if(this.value.length) {
        this.parentElement.className = "";
    } else {
     this.parentElement.className = "empty";   
    }
    });
}
@media print {
    .empty {
        display: none;
    }
}
<div class="empty">Name: <input class="field"></div>
<div class="empty">Field: <input class="field"></div>
<div class="empty">Foo: <input class="field"></div>

(Try adding content to a field but leave some empty before pressing ctrl+p. The empty fields should not appear in the print preview)

If jQuery is being used, the selectors and looping in the JavaScript code can be simplified as shown below:

$(".field").on("keyup", function () {
    $this = $(this);
    if ($this.val().length) {
        $this.parent().removeClass("empty");
    } else {
        $this.parent().addClass("empty");
    }
});

Answer №2

To detect the window.print event and utilize jquery or javascript to identify and hide empty inputs, you can monitor for the `window.print` event.

(function() {
    var beforePrint = function() {
        $('input').each(function(i, el) {
            if ($(el).val() == '') {
                $(el).hide();
            }
        });
    };
    var afterPrint = function() {
        $('input').show();
    };

    if (window.matchMedia) {
        var mediaQueryList = window.matchMedia('print');
        mediaQueryList.addListener(function(mql) {
            if (mql.matches) {
                beforePrint();
            } else {
                afterPrint();
            }
        });
    }

    window.onbeforeprint = beforePrint;
    window.onafterprint = afterPrint;
}());

Link: https://jsbin.com/gacikezulo/edit?html,js,console,output

For more information, refer to this article here. The provided script is expected to function across browsers except for Opera.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Retrieving information from a JSON object in Angular using a specific key

After receiving JSON data from the server, I currently have a variable public checkId: any = 54 How can I extract the data corresponding to ID = 54 from the provided JSON below? I am specifically looking to extract the values associated with KEY 54 " ...

Error: Objects cannot be used as constructors

An Azure Function using JavaScript HTTP Trigger posts activity in a Slack online community for customers. It has been functioning successfully for many years, but after upgrading from version ~2 to ~4, it started throwing an error stating Entities is not ...

Verify if there are multiple elements sharing the same class and initiate a certain action

I am working with three products that have a similar structure: tickbox | label (same text but different value) | Qty dropdown (different input name) These products fall into three different label "classes": 1st - <label for="related-checkbox-708745 ...

Dealing with an Incorrect Date in JavaScript

After working on a JavaScript logic to extract date and time from certain values, I realized that my approach needed some adjustments. Initially, I parsed the DateTime and converted it to a string. Then, I split the string to retrieve the date component. ...

use javascript to color the image based on a specified number or percentage

Looking for a method to dynamically fill an image based on a percentage. Is there a dynamic approach or is it simpler to create images at specific intervals? I am working with Angular and need to set the percentage of a 1 to 5 rating system from AJAX. h ...

Retrieve the binary file data that was sent via Postman using Node.js/Express.js

I am currently testing file uploading in my backend system. I am using Postman to send binary data as a file in the request body, and now I need to extract this data from the POST request. req.body The above code snippet returns a binary buffer that look ...

Is it feasible to adjust the placement of an alert box or add an animation to it?

Is it possible to animate an alert box? I tried applying animation to the alert box, but it doesn't seem to work. I searched online for information on this but couldn't find anything. Can you help me achieve animated alerts? alert(' ur mes ...

Using discord.js within an HTML environment can add a whole new level of

I'm in the process of creating a dashboard for discord.js, however, I am facing difficulties using the discord.js library and connecting it to the client. Below is my JavaScript code (The project utilizes node.js with express for sending an HTML file ...

How to position text in the center of an image and ensure it is responsive?

I am currently in the process of trying to center the text "WHAT" over the image in col-2. <div class="row"> <div class="col-2"> <div class="stackParent"> <img class="stack-Img" ...

Structural engineering for massive webpage

Currently I am in the process of building a large page using AngularJS. As I plan out the architecture for this page, I am debating which approach would be most effective. The page consists of 3 distinct blocks with various functionalities, but the prima ...

magnific popup: trigger the display by clicking on an element other than the image

A recent request from the client calls for the image caption to cover the thumbnail fully when hovered over. To meet this requirement, I now need to enable clicking on the caption to open Magnific Popup rather than using the <a> tag. Here is what I h ...

A guide on extracting data from a customized HTML table on the client side and sending it to the Flask backend

I am looking to implement a feature where users can add as many rows as they want and input information into them. Once the user has finished adding the desired data, I need to process it using Flask on the server-side. Can someone please provide guidanc ...

What is the best way to integrate my PHP regular expression into Node.js code?

I recently encountered an issue when trying to convert a regular expression from PHP to Node.js. The output I'm receiving in Node.js is different from what I expect, and I suspect it has to do with my implementation of PREG_SET_ORDER in Node.js. Here ...

An insightful guide on effectively binding form controls in Angular using reactive forms, exploring the nuances of formControlName and ngModel

Here is the code snippet: list.component.html <form nz-form [formGroup]="taskFormGroup" (submit)="saveFormData()"> <div nz-row *ngFor="let remark of checklist> <div nz-col nzXXl="12" *ngFor="let task of remark.tasks" styl ...

Tips for combining text and variable outcomes in printing

I created a calculator that is functioning correctly and displaying results. However, I would like to include a text along with the results. For example: You spent "variable result" dollars in the transaction. Currently, the results are shown only after ...

How can I fetch and reference multiple local JSON files in Vue using Axios?

I am currently utilizing vue for prototyping some HTML components. Is there a method to make Vue detect two separate JSON files? vue.js var vm = new Vue({ el: '#douglas-laing', data: { products: [], contentPanels: [] }, created() ...

What is the reason for Next.js and Gatsby.js necessitating the installation of Node.js, while React.js does not have that requirement?

Have you ever thought about the connection between Next.js and Gatsby.js, both being built on React.js? Could it be that the development environments are Node applications themselves? Or maybe there's something else I'm not seeing? While I have ...

Can the Route be modified in Next.js?

I have developed search functionality that navigates to "/search/xxxx", but it is located in the header. Every time I perform a search, the route gets repeated and becomes "/search/search/xxx". Could you suggest any way other than usin ...

Operating PHP program from html on Beaglebone Black Rev C Debian

I've created a JavaScript program that utilizes node.js to manage GPIO from an IO.html page to the beaglebone. I simply initiate the JavaScript with "node myscript.js". Now, I'm looking to incorporate a PHP file that will store data from the IO. ...

The output of new Date() varies between app.js and ejs

app.get("/test",function(req,res){ var d = new Date(); res.send(d); }); When I access mydomain/test, it displays the output "2019-03-19T04:50:47.710Z" which is in UTC. app.get("/testejs",function(req,res){ res.render("testejs");}); Below is the content ...