Developer
Developer

Reputation: 8646

Unable to display image using javascript

net code as follows

<asp:Image runat="server" ID="img1" ImageUrl="~/Images/important.gif" />
    <asp:Button ID="btn" runat="server" Text="print" />

and my javascript is as follows

<script type="text/javascript">
    function printIt() {
        var win = window.open('', 'Image', 'resizable=yes,...');
        if (win) {
            //var imgID = '<%= img1.ClientID %>';
            var imageControl = document.getElementById('<%=img1.ClientID%>').src;
            win.document.write(imageControl);
            win.document.close();
            win.focus();
            win.print();
        }
        return false;
    }
</script>

// updated code as per vitoshabg answer

<script type="text/javascript">
    function printIt() {
        var win = window.open('', 'Image', 'resizable=yes,...');
        if (win) {
            //var imgID = '<%= img1.ClientID %>';
            var imageControl = document.getElementById('<%=img1.ClientID%>').src;
            win.write('<img src="' + imageControl + '">');
            //win.write(imgParent);
            win.document.close();
            win.focus();
            win.print();
        }
        return false;
    }
</script>

But instead of the image I am getting the url can some one help me to get the image here

Upvotes: 1

Views: 367

Answers (3)

vitoshabg
vitoshabg

Reputation: 26

var imageControl = document.getElementById('<%=img1.ClientID%>').src;

Here you get the 'src' attribute of the element returned by getElementById.

You can create the new image with

win.document.write('<img src="' + imageControl + '">');

Upvotes: 1

Rookie Programmer Aravind
Rookie Programmer Aravind

Reputation: 12154

Bug removed ;)

<script type="text/javascript">
    function printIt() {
        var win = window.open('', 'Image', 'resizable=yes,...');
        if (win) {
            //var imgID = '<%= img1.ClientID %>';
            var imageControl = document.getElementById('<%=img1.ClientID%>');
            win.document.write(imageControl);
            win.document.close();
            win.focus();
            win.print();
        }
        return false;
    }
</script>

Upvotes: 0

You are getting the URL because you have .src on the end of this line:

var imageControl = document.getElementById('<%=img1.ClientID%>').src;

Change it to this to get the image control:

var imageControl = document.getElementById('<%=img1.ClientID%>');

Upvotes: 0

Related Questions