简体   繁体   中英

How to print content of textbox in IE9 in javascript

I have to print a text box with its value using JavaScript when user enter the value at run time but the below code is not compatible with IE9+ textbox is within div tag

Print:function()
{
     var divtoprint = document.getElementById('div1');

     var popupWin = window.open('', '_blank', 'width=500,height=400');
     popupWin.document.open();
     popupWin.document.write('<html><body onload="window.print()">' + divtoprint.innerHTML + '</html>');
     popupWin.document.close();
 }

Please can you help?

I have changed :

<!DOCTYPE html>
<html>
<head>
<script>
function print(){
     var divtoprint = document.getElementById('main-div').innerHTML;
     alert(divtoprint);
     var popupWin = window.open('', '_blank', 'width=500,height=400');
     popupWin.document.open();
     popupWin.document.write('<html><body onload="window.print()">' + divtoprint + '</html>');
     popupWin.document.close();
 }
</script>
</head>
<body>
 <div>
 <div id="main-div">
    <input type="text" name="FirstName" value="Mickey">
    </div>
    <input type="button" value=" Print Terms " onClick="print()">
</div>

</body>
</html>

and it works f9 in ie9,ie10.

here is the screen shot in my ie 10:

在此处输入图片说明

and this: 在此处输入图片说明

IE has some strict validation of html. Chrome, firefox and the other browsers are not so strict.

In your code you are missing the closing body tag. You will need to this tag and i sure your code will work in IE.

Replace:

popupWin.document.write('<html><body onload="window.print()">' + divtoprint.innerHTML + '</html>');

By:

popupWin.document.write('<html><body onload="window.print()">' + divtoprint.innerHTML + '</body></html>');

At the end of the line I added the closing tag.

I really doubt this can be done to be honest. Besides, a common practice for printing webpages is attaching a stylesheet for printing, in which you are hiding all elements but the ones you want to print.
Here is a nice blog article about that:
print stylesheets

Here is a quick example:

<!DOCTYPE html>
<html>
<head>
    <style media="print">
        .noprint { display: none; }
    </style>
</head>
<body">
    <div>
        <div id="main-div">
            <input type="text" id="mytextbox" name="FirstName" value="Mickey"/>
        </div>
        <input type="button" class="noprint" value=" Print Terms " onClick="window.print()">
    </div>
</body>

Now if your user goes to "print preview" in their browser, they won't see the "print" button (and the same way the page will be printed when they click "print" button on the page)

I hope that will help you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM