2017-08-02 103 views
0

这是我正在尝试修复的示例代码。在打印屏幕中,我无法看到在input文本字段中输入的文本。任何解决方案将不胜感激。如何在打印预览中获取输入文本字段值?

var divToPrint=document.getElementById('div1Id'); 

if (divToPrint != null && divToPrint != "") { 
    var newWin=window.open('','Print-Window'); 
    newWin.document.open(); 
    newWin.document.write('<html><body onload="window.print()">'+divToPrint.innerHTML+'</body></html>'); 
    newWin.document.close(); 
    newWin.close();  
} 
+0

'divToPrint.innerHTML'应该是'divToPrint.value',因为您想从该输入中获得实际值 – Jer

+0

输入文本字段没有'innerHTML'属性,您应该使用'.value'获取输入文本值 –

+0

注意:'divToPrint'永远不会等于一个字符串,('!=“”'),因为它是对'getElementById'的调用的结果,它返回一个元素或null。你的条件可以简单地为'if(divToPrint){'。 – Utkanos

回答

0

使用jquery.print.js库并在您的自定义函数中调用此函数$ .print(“#id”);

+0

这就是我需要的..谢谢nayeem! – krish

0

文本框和CheckBox控件,你必须得到value,而不是innerHTML的

var divName = document.getElementById('div1Id') 
    var originalContents = document.body.innerHTML; 
    var inpText = document.getElementsByTagName("input")[0].value; 
    var printContents = document.getElementById(divName).innerHTML; 
    printContents += inpText; 

    newWin.document.open(); 
    newWin.document.write('<html><body 
    onload="window.print()">'+printContents+'</body></html>'); 
    newWin.document.close();  
0

你有这样的script

var divToPrint=document.getElementById('div1Id'); 

if (divToPrint != null && divToPrint != "") { 
    var newWin=window.open('','Print-Window'); 
    newWin.document.open(); 
    newWin.document.write('<html><body onload="window.print()">'+divToPrint.innerHTML+'</body></html>'); 
    newWin.document.close(); 
    newWin.close();  
} 

,你复制的内部HTML,但是,值不那里。让我们确保这些值是正确的,如下所示:

var divToPrint=document.getElementById('div1Id'); 

//Gather input values and inputs 
var inputValues = []; 
var inputs = divToPrint.getElementsByTagName("input"); 
for (var index = 0; index < inputs.length; index++) inputValues.push(inputs[index]); 

//Generate script of page 
var script = 'var inputValues = ' + JSON.stringify(inputValues) + ';'; 

script += 'var inputs = document.getElementsByTagName("input");' + 
      'for (var index = 0; index < inputs.length; index++) ' + 
      'inputs[index].value = inputValues[index];'; 

if (divToPrint != null && divToPrint != "") { 
    var newWin=window.open('','Print-Window'); 
    newWin.document.open(); 
    newWin.document.write('<html><body onload="' + script + 'window.print()">'+divToPrint.innerHTML+'</body></html>'); 
    newWin.document.close(); 
    newWin.close();  
} 

代码未经测试,请让我知道是否有错字。

+0

正如我在我以前的评论中指定的divToPrint是div的ID,其中包含表,文本字段等手动设置脚本中的所有字段值是位过程,任何其他方式来解决这 – krish

+0

@krish需要多少毫秒?你有多少输入? –

+0

使用.print()(jQuery.print.js)得到了解决方案..感谢回复 – krish