E7AD
E7AD

Reputation: 67

Add a Click Event to elements added to the DOM

 var myOP = '<div>';
 for (var i = 0; i < op.length; i++) {
     myOP += '<div>';
     myOP += '<div id="myBTN-' + [i] + '">' + op[i]['Field1'] + '</div>';
     myOP += '<div id="blah-' + [i] + '">' + op[i]['Field2'] + '</div>';
     myOP += '</div>';
 }
 myOP += '</div>';
 $("#myBTN-" + i).click(function () {
     $('#blah-' + i).toggle("slow");
 });
 $('#container').html(myOP);

I'm trying to get the click function to fire on the elements i'm created w/ the above for loop. Can anyone point me in the right direction?

Upvotes: 0

Views: 110

Answers (6)

KooiInc
KooiInc

Reputation: 122996

As long as the element is just a String, you won't be able to add a handler. You have to add the handler after $('#container').html(myOP);

You could try exploring the idea of event delegation. Using that, your could do something like:

$('#container').on('click', function(e){
  e = e || event;
  var from = e.target || e.srcElement, i;
  if (from.id && /^mybttn/i.test(from.id)){
   i = +((from.id.match(/\d{0,}$/)||[-1])[0]);
   if (i>=0){
    $('#blah'+i).toggle('slow');
   }
  } 
});​

​Demo

Alternatively you could

 $('#container').html(myOP);
 $('div[id^="myBTN-"]').on('click',function(){
     $('#blah-' + this.id.match(/\d{0,}$/)[0]).toggle("slow");
 });

Upvotes: 2

Eric
Eric

Reputation: 97691

You'd do better to build the element on the fly:

 var container = $('<div>');
 for (var i = 0; i < op.length; i++) {
     container.append(
         $('<div>').append(
             $('<div>').text(op[i]['Field1']).click(function() {
                 $(this).next('div').toggle("slow"); 
             }),
             $('<div>').text(op[i]['Field2'])
         )
     );
 }
 $('#container').empty().append(container);

Upvotes: -1

NedStarkOfWinterfell
NedStarkOfWinterfell

Reputation: 5243

When you re trying to attach events added dynamically, a simple .click() won't do, you have to use on:

$("#newElementparent").on('click', "#newElement", function() {});

Upvotes: 0

Draculater
Draculater

Reputation: 2278

jQuery's .on() method will bind to appended elements if used properly. http://api.jquery.com/on/

<div id="existingParent">
    <!--<div class="added-later">Hi!</div>-->
    <!--<div class="added-later">Hi!</div>-->
</div>

To listen for events on the added-later elements

$('#existingParent').on('click hover','.added-later', myFunction);

The method must be bound to an element that exists. $('body') can be used here, but at the cost of some performance I'd imagine.

Upvotes: 1

kannix
kannix

Reputation: 5167

Do something like this:

var myOP = '<div>';
for (var i = 0; i < op.length; i++) {
    myOP += '<div>';
    myOP += '<div id="myBTN-' + [i] + '">' + op[i]['Field1'] + '</div>';
    myOP += '<div id="blah-' + [i] + '">' + op[i]['Field2'] + '</div>';
    myOP += '</div>';
}
myOP += '</div>';
$(myOP).appendTo('#container').find('div[id^="myBTN"]').click(function () {$(this).next().toggle("slow")});

Upvotes: 0

Shlomi Komemi
Shlomi Komemi

Reputation: 5545

after you save the html into #container use this:

$('[id^="myBTN-"]', '#container').click(function () {
    $(this).closest('[id^="blah-"]').toggle('slow');
});

Upvotes: 1

Related Questions