You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

HTML表单打印问题:textarea内容无法显示及打印的排查求助

问题分析与解决方案

你的代码无法打印textarea内容的核心原因是:CopyElem函数只同步了文本输入框、日期输入框和复选框的状态,完全遗漏了对textarea元素的处理。

当你通过$(elem).html()获取表单的HTML代码时,textarea的用户输入内容并不会自动同步到它的标签内部文本中,导致弹窗里的textarea是空的,自然打印预览看不到内容。

修改后的代码

只需要在CopyElem函数中添加处理textarea的逻辑即可:

<script type="text/javascript">
 function CopyElem(elem)
 {
     $('form input[type=text]').each(function() {
       $(this).attr('value', $(this).val());
     });

     $('form input[type=date]').each(function() {
       $(this).attr('value', $(this).val());
     });

     $('form input[type=checkbox]').each(function() {
       $(this).attr('checked', $(this).prop("checked"));
     });

     // 新增:同步textarea的输入内容到标签文本
     $('form textarea').each(function() {
       $(this).text($(this).val());
     });
 }
 function PrintElem(elem)
 {
     Popup($(elem).html());
 }

 function Popup(data) 
 {
     var mywindow = window.open('', 'myfrm');
     mywindow.document.write('<html><head><title>Behandelformulier</title>'); 
     mywindow.document.write('</head><body >');
     mywindow.document.write(data);
     mywindow.document.write('</body></html>');

     mywindow.document.close(); // necessary for IE >= 10
     mywindow.focus(); // necessary for IE >= 10

     mywindow.print();
     mywindow.close();

     return true;
 }
</script>

关键说明

  • textarea的用户输入内容存储在value属性中,但HTML结构里它的显示内容是标签内部的文本(如<textarea>这里是内容</textarea>),所以需要用text()方法将用户输入的val()同步到标签内部。
  • 确保打印逻辑的执行顺序:先调用CopyElem同步所有表单元素的状态,再调用PrintElem获取HTML并打印。比如打印按钮的点击事件可以写成:
<button onclick="CopyElem('form'); PrintElem('form');">打印表单</button>

内容的提问来源于stack exchange,提问作者Peter Kuipers

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 02:41:28