purple11111
purple11111

Reputation: 719

clone php foreach elements with javascript

I got a foreach 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.

    <?php
      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>".
                  "</div>".
                "</a>".
              "</li>";
      }
    ?>

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;
      original.parentNode.appendChild(clone);
    }

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 $value used for the var original is simply the last item of the foreach.

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

Upvotes: 0

Views: 151

Answers (1)

Ismail RBOUH
Ismail RBOUH

Reputation: 10450

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;
    original.parentElement.appendChild(clone);
}

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.

Upvotes: 2

Related Questions