UserNameHere
UserNameHere

Reputation: 85

Add on click events to dynamically created Buttons

I currently have a HTML page, 2 JS files and a php file. The HTML calls the 1st JS file that calls the PHP which dynamically creates the page. On the generated page there are several items with buttons underneath them.

I want these buttons to trigger a function in the 2nd JS file.

PHP File:

<head> 
<script type="text/javascript" src="js2.js"></script> 
</head> 
<?php
$i = 0;
for($i=0,$i<3,i++)
{
   echo 'Do '.$i;
   echo '<input value="Do it" type="button" onclick="doit('.$i.')"/>';
}
?>

The second JS file:

function doit(p1) 
{       
   //code here  
}

Edit: Looking into it further this works just there was an error inside JS function that caused it to appear as if it did nothing.

Upvotes: 0

Views: 92

Answers (1)

Timusan
Timusan

Reputation: 3445

I'm guessing your events are not firing on the newly inserted elements?

The problem is as follows: You load some HTML which is rendered by the browser. When the rendering is complete, the DOM is ready loading and all JavaScript handlers are set.

Next, you dynamically insert new pieces of the DOM via your first JS (and through an AJAX callback I presume?). These new pieces come after the original DOM has finished loading and thus these new buttons do not have any handlers set on them by JS.

If you use a framework like jQuery you could use .live() or the newer .on() handlers to attach a new event to these newly inserted elements. If you wish to support plain JavaScript, however, you could register events using the addEventListener. If you use the latter solution, be careful for browser support below IE9 though.

An example usage of plain JavaScript would be (your second external JS file):

var el = document.getElementsByClassName("yourinputclass");
el.addEventListener("click", doit(el.data), false);

Here el is the input(s) you wish to target. The targeting is done through the class name of the elements. Your element would also need an extra data attribute in the case of the above snippet. So an example line in your PHP loop would be:

echo '<input class="yourinputclass" value="Do it" type="button" data="'.$i.'" />';

Upvotes: 2

Related Questions