Steve Kim
Steve Kim

Reputation: 5591

jQuery Clone with different PHP array value

So, I have the following PHP values:

PHP:

<?php
$data = array("Mike","Sean","Steve");
?>

<script type="text/javascript">
    var tag_data = <?php echo json_encode($data); ?>;
</script>

<div class="container">
    <div class="content">
       <p></p>
    </div>
</div> 

JS:

????

So, I am trying to use the first value (Mike) in the <p>, then repeat the whole thing to show the second value as below while keeping the previously generated container.

<div class="container">
    <div class="content">
       <p>Mike</p>
    </div>
</div> 
<div class="container">
    <div class="content">
       <p>Sean</p>
    </div>
</div> 
<div class="container">
    <div class="content">
       <p>Steve</p>
    </div>
</div> 

I learned that I can use clone in jQuery to repeat div, but I am not sure how to do it properly.

I want to repeat the whole container with the subsequent array value.

Can someone show me a basic version of how to achieve this?

Upvotes: 1

Views: 113

Answers (1)

Alexander O&#39;Mara
Alexander O&#39;Mara

Reputation: 60527

Something like this should do the trick! Basically, you .clone the element, change the content, insert the clone back into the DOM, and remove the template. Remember to put this JavaScript after the template, or use the jQuery document ready functionality.

var tag_data = ["Mike","Sean","Steve"]; // <?php echo json_encode($data); ?>;

// Get the template element, you will probably want to use a more-specific selector.
var $containerTemplate = $('.container');
// Itterate over your array.
tag_data.forEach(function(person) {
    // CLone the template element.
    var $cloned = $containerTemplate.clone();
    // Set the text from the array.
    $cloned.find('p').text(person);
    // Insert in order where the template elements comes from.
    $cloned.insertBefore($containerTemplate);
});
// Remove the template element.
$containerTemplate.remove();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<div class="container">
    <div class="content">
       <p></p>
    </div>
</div>

Upvotes: 2

Related Questions