Parvathy
Parvathy

Reputation: 2465

Getting previous values from windows.print() in javascript

The Problem:

When ever I choose the print button then this code will work and pop up for print appears after choosing print it's working fine.

The problem is, if I choose the Cancel button of windows print option and if I'm going to print a new page then it is showing the cancelled page, not the new one.


Print Screen Screenshot

Question

Is there any option to clear or remove what I write in this line win.document.write(inf);?

Code

Here is the code, it will always show haiiiiii in print preview can't update that text field.

Script:

function displayMessage(printContent) {     
    var inf = printContent;
    document.innerHTML="";
    win = window.open('about:blank');
    win.document.write(inf);
    win.print();
    win.close();
    alert(inf);
} 

HTML

<div id="formdiv">
    <form id="form1" name="form1" method="post" action="">
        <div id="printadform">
            <table width="997" border="1">
                <tr>
                    <th colspan="4" bgcolor="#999999"><div align="center" class="style1"><input type ="text" value="haiiiiiii"/></div></th>
                </tr>
            </table>
        </div>
    </form>
</div>
 
<a class="btn btn-primary" id = "print" onclick="displayMessage(formdiv.innerHTML)">Print</a>
<a href="#/branch/list/{{student.branch}}" class="btn" id="cancel">Cancel </a></div>

Upvotes: 1

Views: 444

Answers (1)

super
super

Reputation: 2328

Try this, Text elements don't have an innerHTML property so you have to set the value filed.

Html:

<div id="formdiv">
    <form id="form1" name="form1" method="post" action="#">
        <div id="printadform">
            <table style="width:80%;border: 1px solid black;">
                <tr>
                    <th colspan="4" style="background-color:#999;">
                        <span style="text-align:center;">
                            <input id="box" type="text" value="Hai" />
                        </span>
                    </th>
                </tr>
            </table>
        </div>
    </form>
</div>

Script:

function displayMessage() {    
    var val = box.value; //get the input box value
    box.setAttribute('value', val); //set value attribute into input
    var inf = formdiv.innerHTML;
    document.innerHTML = "";
    var win = window.open('about:blank');
    win.document.write(inf);
    win.print();
    win.close();
}

Demo

Upvotes: 1

Related Questions