Table of Contents
JavaScript print form: Solve the problem of content update failure
Home Web Front-end HTML Tutorial Why does the modified content fail to work when JavaScript prints a form?

Why does the modified content fail to work when JavaScript prints a form?

Apr 05, 2025 am 09:33 AM
Why

Why does the modified content fail to work when JavaScript prints a form?

JavaScript print form: Solve the problem of content update failure

When printing forms using JavaScript, sometimes you will encounter the problem that the form content (such as textarea text fields and check boxes) is updated, but the print result shows the old value. This article analyzes the causes of this problem and provides solutions.

Problem description:

Users enter or modify content in the form (including text and checkbox check status), but the results of the printout do not reflect these changes.

Sample code (there is a problem):

<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<div id="divKanZhengPanel-binli">
  <div class="checkDiv">
    <label>Right position</label>
    <label>External slant</label>
    <label>Inner slant</label>
    <label>Outer hidden oblique</label>
    <label>Implicit oblique</label>
  </div>
</div>
<button id="dw">Click me to print</button>

<script>
  document.getElementById('dw').addEventListener('click', function() {
    let docHtml1 = $("#divKanZhengPanel-binli").prop("outerHTML");
    $('#print-iframe').remove(); 
    let iframe1 = document.createElement('IFRAME');
    let doc1 = null;
    iframe1.id = "print-iframe";
    iframe1.style = 'position:absolute;width:0px;height:0px;left:-0px;top:-0px;visibility: auto;';
    document.body.appendChild(iframe1);
    doc1 = iframe1.contentWindow.document;
    doc1.write(docHtml1);
    doc1.close();
    iframe1.contentWindow.focus();
    iframe1.contentWindow.print();
  })
</script>
Copy after login

Cause of the problem:

The original code uses outerHTML to get the HTML content of the form element. This method only gets the static HTML structure of the element and does not contain dynamically updated form values.

Solution:

Use cloneNode(true) method to clone the form element. cloneNode(true) copies the element and all its child nodes and attributes, including the current value of the form element.

Improved code:

<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">

<div id="divKanZhengPanel-binli">
  <div class="checkDiv">
    <label>Right position</label>
    <label>External slant</label>
    <label>Inner slant</label>
    <label>Outer hidden oblique</label>
    <label>Implicit oblique</label>
  </div>
</div>
<button id="dw">Click me to print</button>

<script>
  document.getElementById('dw').addEventListener('click', function() {
    $('#print-iframe').remove(); 
    let iframe1 = document.createElement('IFRAME');
    let doc1 = null;
    iframe1.id = "print-iframe";
    iframe1.style = 'position:absolute;width:0px;height:0px;left:-0px;top:-0px;visibility: auto;';
    document.body.appendChild(iframe1);
    setTimeout(function() { // 使用setTimeout确保iframe加载完成
      doc1 = iframe1.contentWindow.document;
      doc1.body.appendChild(document.querySelector('#divKanZhengPanel-binli').cloneNode(true));
      doc1.close();
      iframe1.contentWindow.focus();
      iframe1.contentWindow.print();
    });
  })
</script>
Copy after login

By using cloneNode(true) , the printed form content will accurately reflect the user's modifications made on the page. The setTimeout function has been added to ensure that the print operation is performed after the iframe content is loaded to avoid the blankness of the print content. Make sure you introduce the jQuery library in your code because the code uses the $ symbol. If jQuery is not used, you need to use native JavaScript methods to select elements.

The above is the detailed content of Why does the modified content fail to work when JavaScript prints a form?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Unable to log in to mysql as root Unable to log in to mysql as root Apr 08, 2025 pm 04:54 PM

The main reasons why you cannot log in to MySQL as root are permission problems, configuration file errors, password inconsistent, socket file problems, or firewall interception. The solution includes: check whether the bind-address parameter in the configuration file is configured correctly. Check whether the root user permissions have been modified or deleted and reset. Verify that the password is accurate, including case and special characters. Check socket file permission settings and paths. Check that the firewall blocks connections to the MySQL server.

How to recover data after SQL deletes rows How to recover data after SQL deletes rows Apr 09, 2025 pm 12:21 PM

Recovering deleted rows directly from the database is usually impossible unless there is a backup or transaction rollback mechanism. Key point: Transaction rollback: Execute ROLLBACK before the transaction is committed to recover data. Backup: Regular backup of the database can be used to quickly restore data. Database snapshot: You can create a read-only copy of the database and restore the data after the data is deleted accidentally. Use DELETE statement with caution: Check the conditions carefully to avoid accidentally deleting data. Use the WHERE clause: explicitly specify the data to be deleted. Use the test environment: Test before performing a DELETE operation.

Navicat's method to view MongoDB database password Navicat's method to view MongoDB database password Apr 08, 2025 pm 09:39 PM

It is impossible to view MongoDB password directly through Navicat because it is stored as hash values. How to retrieve lost passwords: 1. Reset passwords; 2. Check configuration files (may contain hash values); 3. Check codes (may hardcode passwords).

How to install mysql in centos7 How to install mysql in centos7 Apr 14, 2025 pm 08:30 PM

The key to installing MySQL elegantly is to add the official MySQL repository. The specific steps are as follows: Download the MySQL official GPG key to prevent phishing attacks. Add MySQL repository file: rpm -Uvh https://dev.mysql.com/get/mysql80-community-release-el7-3.noarch.rpm Update yum repository cache: yum update installation MySQL: yum install mysql-server startup MySQL service: systemctl start mysqld set up booting

How to view database password in Navicat for MariaDB? How to view database password in Navicat for MariaDB? Apr 08, 2025 pm 09:18 PM

Navicat for MariaDB cannot view the database password directly because the password is stored in encrypted form. To ensure the database security, there are three ways to reset your password: reset your password through Navicat and set a complex password. View the configuration file (not recommended, high risk). Use system command line tools (not recommended, you need to be proficient in command line tools).

Centos stops maintenance 2024 Centos stops maintenance 2024 Apr 14, 2025 pm 08:39 PM

CentOS will be shut down in 2024 because its upstream distribution, RHEL 8, has been shut down. This shutdown will affect the CentOS 8 system, preventing it from continuing to receive updates. Users should plan for migration, and recommended options include CentOS Stream, AlmaLinux, and Rocky Linux to keep the system safe and stable.

mysql cannot terminate the process mysql cannot terminate the process Apr 08, 2025 pm 02:48 PM

The kill command in MySQL sometimes fails because of the special process status and improper signal level. Methods to effectively terminate the MySQL process include: confirming the process status, using the mysqladmin command (recommended), using kill -9 with caution, checking system resources, and in-depth troubleshooting of error logs.

Navicat's method to view SQLite database password Navicat's method to view SQLite database password Apr 08, 2025 pm 09:36 PM

Summary: Navicat cannot view SQLite passwords because: SQLite does not have traditional password fields. SQLite's security relies on file system permission control. If the file password is forgotten, it cannot be retrieved (unless the database is encrypted, the key is required).

See all articles