blazerix blazerix - 2 months ago 10
CSS Question

How to dynamically create objects on the fly with click of a button

I'm trying to create 2 rows of 6 rectangles (considered to be one object).

I also want to add a plus button, so that when the user clicks on either end, a new set of rectangles appear above or below the original ones. (depending on which plus button they click on)

So I am trying to achieve the following:

enter image description here
What I have tried/found so far:



$(function () {
$(".repeat").on('click', function (e) {
e.preventDefault();
var $self = $(this);
$self.before($self.prev('table').clone());
//$self.remove();
});
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<form>
<div class="repeatable">
<table border="1">
<tr>
<td>
<input type="text" name="userInput[]" />
</td>
</tr>
</table>
<button class="repeat">Add Another</button>
</div>
<input type="submit" value="Submit" />
</form>





The above example only works for forms. Does anyone know how I can go about making this work for what I want?

Answer

I modified your code to allow add to top, or add below.

I edited your event listener to check whether the button has a specific class. If so, either add above or below. It also listens to "body" click, because new DOM elements won't have event listeners attached:

$("body").on('click', ".repeat", function (e) { //other stuff here}

Also, changed your HTML so it wasn't dependent on "form", you could swap out the element types as long as the classes remain.

$(function () {
    $("body").on('click', ".repeat", function (e) {
        e.preventDefault();
        var $self = $(this);
        var $parent = $self.parent();
        if($self.hasClass("add-bottom")){
          $parent.after($parent.clone());
        } else {
          $parent.before($parent.clone());
        }
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>  
  <div class="container">
    <div class="repeatable">
      <button class="repeat add-top">Add above</button>
        <table border="1">
            <tr>
                <td>
                    <input type="text" name="userInput[]" />
                </td>
            </tr>
        </table>
        <button class="repeat add-bottom">Add below</button>
    </div>
  </div>

Comments