views:

9589

answers:

5

I have a page with an anchor tag. In my JavaScript I am setting the HREF attribute of the anchor tag dynamically based on some if-else conditions. Now I want to invoke the click event of the anchor tag programmatically. I used the below code, but was not successful.

var proxyImgSrc="CostMetrics.aspx?Model=" + model +"&KeepThis=true&TB_iframe=true&height=410&width=650";

document.getElementById("proxyAnchor").href=proxyImgSrc;
document.getElementById("proxyAnchor").onclick;

Can any one tell me how to go ahead? I have a jQuery light box implementation(thickbox) on this link.

Kindly advise. Thanks in advance.

+1  A: 

I believe you want to invoke the click event. Not the "onClick." Also, be sure to include the parenthesis () when you're invoking a method. Don't confuse methods (which end with ( and )) with attributes and properties which do not end with ( and ).

// Using jQuery - Which you tagged...
$("#proxyAnchor").attr("href", proxyImgSrc).click();
Jonathan Sampson
Yes.Click event
Shyju
+9  A: 

If you have jquery installed then why not just do this:

$('#proxyAnchor').click();

As to why your original code is not working - it is probably because you are calling 'onclick', and not 'onclick()'. Without the parenthesis javascript will return whatever is assigned to the onclick property, not try to execute it.

Try the following simple example to see what I mean:

var f = function() { return "Hello"; };

alert(f);
alert(f());

The first will display the actual text of the function, while the second will display the word "Hello" as expected.

samjudson
Why the downvote?
samjudson
Thanks Samjudson.IT worked
Shyju
+3  A: 

You should call click event like that :

document.getElementById("proxyAnchor").click();
// $('#proxyAnchor').click();

but in your case you should set window's location to redirect page, if you want that.

Canavar
A: 

I believe this is what you're after:

        var proxyImgSrc="CostMetrics.aspx?Model=" + model +"&KeepThis=true&TB_iframe=true&height=410&width=650";
        $("#proxyAnchor").attr('href', proxyImgSrc).trigger("click");;
karim79
A: 

For an immediate page change, you can also do this:

var proxyImgSrc= "CostMetrics.aspx?Model=" + model + "&KeepThis=true&TB_iframe=true&height=410&width=650";
window.location = proxyImgSrc;

Here's an example from W3 Schools: http://www.w3schools.com/js/tryit.asp?filename=tryjs_location

Darren Torpey