2017-08-02 107 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