views:

21

answers:

1

I have the following links (buttons) on a page that I need to instead of it going to the link to call a function instead and pass the url of the respective button clicked via a variable to that function. There may be more than 3 links (buttons) on the page but they all need to call the same function but pass the respective href valve of the button clicked on. My assumption is I need to do a bind of some sort but not really sure how to do it in jquery. Any help would be appreciated!!!

Edit: Unfortunately there are no id's for any of the anchors but the only way I can say to target the anchors is the begining of the href attribute which will always start with "/ShoppingCart.asp?ProductCode="

<td width="36%" align="right"> 
<a href="/ShoppingCart.asp?ProductCode=884280"> 
<IMG SRC="/v/vspfiles/templates/100/images/buttons/btn_addtocart_small.gif" ALIGN=absmiddle BORDER=0></A> 
</td>

<td width="36%" align="right"> 
<a href="/ShoppingCart.asp?ProductCode=9857%2D116%2D003"> 
<IMG SRC="/v/vspfiles/templates/100/images/buttons/btn_addtocart_small.gif" ALIGN=absmiddle BORDER=0></A> 
</td> 


<td width="36%" align="right"> 
<a href="/ShoppingCart.asp?ProductCode=70367301P"> 
 <IMG SRC="/v/vspfiles/templates/100/images/buttons/btn_addtocart_small.gif" ALIGN=absmiddle BORDER=0></A> 
</td>
+2  A: 

Hi,

You can do this with jQuery pretty easily.

Let's create a sample function:

function someFunction(href) {
    //do something with url
    alert(href);
}

And then in jQuery, you can easily pass the href attribute to the function:

To get all elements starting with that prefix, simply use this code.

$("a[href^='/ShoppingCart.asp?ProductCode']").click(function () {
    var href = $(this).attr('href');
    someFunction(href);
    return false;
});

The return false will prevent the link from going to that page.

Marko
If I have other href's on the page wouldn't I need to target like $("a[href^='/ShoppingCart.asp?ProductCode=']").click(function ()and wouldn't the function need to be function someFunction(href) {instead of function someFunction(url) {??????
Check out my edit
Marko
And inside the custom function you can name the parameter whatever you like, as long as you use the same name inside your function.function blah(foo, bar) { alert(foo + bar);}
Marko
Gonna check it an let you know but it looks like it will work, will let you know!!! THX
I tried it in jsFiddle - http://jsfiddle.net/Vs5qR/
Marko
Works perfect, thx again!!!