views:

405

answers:

2

Hi, I need to call a Javascript function from an a element.. something like this:

href='javascript:myjavascriptfunction();'. I need the Javascript function to get the values from a couple of datepicker controls, build and urlencode a querystring and return it so that it opens into a new window. So far I think I have everything, but I'm struggling with building the URL and returning it correctly. This is my a element so far.

<a href='javascript:myjavascriptfunction();' id="myhyperlink" target="_blank">

In my Javascript function I am building the string and returning it like this:

return queryString;

Result: click the link and a new window opens with the URL of my parent window with the function call name appended to it?

+1  A: 

You need to use window.open() to force a new window, I believe the only reason it's behaving like it is for you is you're telling it to open that javascript in a new window, and it's doing exactly what you're telling it.

After you get your url assembled, do a window.open(urlvar); and you should get what you're looking for.

Also, check out this post for how to make a tidy <a href=""> with an onclick that degrades gracefully. At the minimum, do href="javascript:void(0)" and then onclick="myjavascriptfunction(); return false;".

Pablo
Thanks pablo. that fixed it. Thank you too KinoPiko for you comments. I now have another problem uncovered by fixing this one. Now i am seeing that using the escape function to urlencode the dates from the datepicker controls isn't actually working. any ideas??
danielea
Perhaps that is another question.
Kinopiko
A: 

The return value of a JavaScript function is not available to the browser as the HREF for the link. In order to make this work as you intend, you would have to get the A element in JavaScript and meddle with its HREF. That is possible:

 var link = document.getElementById ("myhyperlink");
 link.href = "http://example.com/" + jiggerypokery ();

where jiggerypokery () is whatever URL you want to make.

However the above is stupid, since it overwrites the link to itself, and the user would probably have to click on it twice anyway. As Pablo says you should be using window.open here, so in myjavascriptfunction ()

var gotopage = "http://example.com/" + jiggerypokery ();
window.open (gotopage);
Kinopiko