-1

This is something I've done 100 times, but I can't spot why it's not binding. I'm creating a itemized list from a TAFFY database.

// get matching data from tfPLdata
var ts="";
var match=0;
tfPLdata({"vType":{likenocase:vType},"vSubType":{likenocase:vSubType}}).each(function (record,recordnumber) {   
    match++;
    ts+="<div class='vWRAP' id='vh_"+recordnumber+"'>";
        ts+="<div class='vTN'>"+record["vTypeName"]+"</div>";
        ts+="<div class='vP'>"+record["vPrice"]+"</div>";
    ts+="</div>";
});     

the result looks like this

<div class='vWRAP' id='vh_0'>
    <div class='vTN'>my corn seed 2</div>
    <div class='vP'>165.00</div>
</div>
<div class='vWRAP' id='vh_1'>
    <div class='vTN'>my corn seed 1</div>
    <div class='vP'>150.00</div>
</div>

then I'm trying to bind CLICK to the class .vWRAP

$(".vWRAP").click(function(){
        console.log("test");
}); 

but it just doesn't fire.

Why?

========================================

I added the code:

$(function() {
      $(".vWRAP").each(function(){
        console.log( $(this).attr("id") );
        $(this).click(function(){
            console.log("test");
        });
      });
});         

and it correctly shows the ID for each .vWRAP. It still won't bind "click" however.

Shawn
  • 2,624
  • 3
  • 22
  • 46

1 Answers1

1

I am going to assume your elements are being added dynamically. To bind click to dynamic elements use the jQuery .on()

$(function () {
    $(document).on('click', '.vWRAP', function() {
        console.log("test");
    });
});

Also just incase you didn't know $(function () { ... }); is a short hand for document ready $(document).ready(function () { ... });.

I also use jQuery instead of $ because it avoids conflict issues.

Ashley Medway
  • 6,659
  • 7
  • 43
  • 63
  • Thank you. I am adding dynamically. (I had to remove the open-parenthesis before 2nd "function" btw) This still does not work. – Shawn Feb 20 '15 at 21:34
  • Sorry the `(` was a typo, edited now. If this code doesn't work then there is something wrong with your code. – Ashley Medway Feb 20 '15 at 21:38
  • 1
    What was happening really didn't have to do with the fact that the data was dynamic. The element that fires the display of #vHelper lost focus and it was going away before the click had a chance to fire. – Shawn Feb 20 '15 at 22:01