purple11111 purple11111 - 1 year ago 126
Javascript Question

clone php foreach elements with javascript

I got a

that generates a list of links now in the top right corner of every link I got a clone button that when clicked should clone that element. The below code in its current format.

foreach ($result as $value) {
list($classname, $origin, $name) = explode('_', $value);
$classname = trim($classname, '[]');
$origin = trim($origin, '[]');
$name = pathinfo($name, PATHINFO_FILENAME);
echo "<li class='audiofile " . $name . " " . $classname . "' id='" . $value . "'>".
"<a class='btn_clone' id='' onclick='repeat()'>#</a>".
"<a href='" . $directoryname . "/" . $value . "'>".
"<img src='images/avatars/" . $classname . ".jpg'>".
"<div class='audiotext'>".
"<span class='audiotitle'>" . $name . "</span>".
"<span class='audioorigin'>" . $origin . "</span>".

This goes together with this js further down the file.

var i = 0;
var original = document.getElementById('<?php echo $value ?>');

function repeat() {
var clone = original.cloneNode(true);
clone.id = "clone" + ++i;

Currently it will clone only the last item of the list no matter what item you clicked the clone button. And that is I think because the
used for the var
is simply the last item of the

So how to make it work with the generated id's in the
. Or if there is another way to make each item clone but keeping the
intact I would really appreciate it to hear it. Thanks in advance for helping.

Answer Source

You can select the element by usin this.parentElement when the click event occurs:

var j = 0;
function repeat(event) {
    var original = event.target.parentNode;
    var clone = original.cloneNode(true);
    clone.id = "clone" + ++j;

And you have to add the event in your onclick attribute:

"<a class='btn_clone' id='' onclick='repeat(event)'>#</a>".
//.......                                   ^ add this

I hope this will help you.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download