LatinCanuck
LatinCanuck

Reputation: 463

Javascript code to Jquery code not working

I have an image that is changed when I click on several links. The following javascript code works well :

<img src="myImage.png" id="mainImg"  /> 

<a href="javascript:;" id="report1_id" onclick="document.getElementById('mainImg').src='http://localhost/convertToReport1.do';">Report1</a>
<a href="javascript:;" id="report2_id" onclick="document.getElementById('mainImg').src='http://localhost/convertToReport2.do';">Report2</a>

But I'm trying to change the code to use Jquery code instead. It calls the same server code as the javascript example. No errors are generated & a png is streamed back. But the image is not updated on the html page. To make things worst, the html moves to the top of the page. In the working javascript code, the image would fresh with a nice ajaxy feel where only the image would change & the rest of the page would not move. My Jquery code is below :

<img src="myImage.png" id="mainImg"  /> 

<a href="" id="report1_id">Report1</a>
<a href="" id="report2_id">Report2</a>

<script type="text/javascript">

    $(document).ready(function(e) { 
        $("#report1_id").click(function(e)     {   
            alert("This Is Report1");
            d = new Date();
            $("#mainImg").attr("src", "http://localhost/convertToReport1.do?"+d.getTime());
        });     

        $("#report2_id").click(function(e)     {   
            alert("This Is Report2");
            d = new Date();
            $("#mainImg").attr("src", "http://localhost/convertToReport2.do?"+d.getTime());
        });             
    });
</script>

Can anyone see what I'm doing wrong? Any help would be appreciated.

Upvotes: 1

Views: 60

Answers (1)

Shomz
Shomz

Reputation: 37711

From your code, the image src should change, but maybe it doesn't change to what you'd like. Make sure that http://localhost/convertToReport1.do returns exactly what you need (ideally, you can specify that in the question itself).

The page jump happens because of the anchors href attribute. Either remove it, or prevent the default anchor behaviour in your click handler function, like this:

$("#report1_id").click(function(e)     {   
    e.preventDefault();  // <--- this is the key, return false would also work at the end
    alert("This Is Report1");
    d = new Date();
    $("#mainImg").attr("src", "http://localhost/convertToReport1.do?"+d.getTime());
});     

See it in action here: http://jsfiddle.net/egvac61c/

Upvotes: 2

Related Questions