How to craft links so they are handled by JQuery in document.ready and not global scope

I recently asked a question here:

Previous question

and the answer determined that my Javascript function was in Global scope and not found inside the document.ready. I am using VB.NET to build the links that are displayed with some of the code being as follows:

sb.Append("<div class=""img-thumbnail"">")
                sb.Append("<a href=""javascript:productPopup('" & Trim(dr.Item("StyleDescription")) & "');"" class=""thumbnail""><img src=""http://placehold.it/100x100"" /></a><h4 class=""thumbnail caption"">" & dr.Item("StyleDescription") & "</h4>")
                sb.Append("<center>" & dr.Item("ststy") & "</center><br />")
                sb.Append("<center>Price: " & FormatCurrency(dr.Item("lowprice"), 2) & " MSRP: " & FormatCurrency(dr.Item("lowMSRP"), 2) & "</center>")
                sb.Append("</div><!-- thumbnail --></div><!-- col-md-2 -->")

Now I was told that in order to put my function inside of document.ready I should use JQuery to handle the click of the link. My question is this:

I am going to need the StyleDescription to be passed to the function so that I can use AJAX to get data out of my database relating to that product. How can I craft the JQuery so that it gets this information correctly regardless of which link is clicked? Thus, let's say I have these links:

<a href="javascript:showProductPopup('STY5901');">Green T-Shirt</a>
<a href="javascript:showProductPopup('STY5915');">Red T-Shirt</a>

How can I convert this to let JQuery handle it and still get the proper StyleDescription value as shown in the above links?

Answers:

Answer

You could make the style number an attribute of the anchor:

<div><a class="product" s="STY5901" href="javascript:void(0);">Green T-Shirt</a></div>
<div><a class="product" s="STY5915" href="javascript:void(0);">Red T-Shirt</a></div>

And then get the attribute value in the click event:

$(document).ready(function(){
    $(".product").click(function(){
        showProductPopup($(this).attr("s"));
    });
});

function showProductPopup(s){
    console.log("called showProductPopup with value: " + s);
}

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.