Question

The below code is for repeating a div. But it does not work. Please help me.

<html>
  <head>
    <script>
      $(".repeat").live('click', function () {
        var $self = $(this);
        $self.after($self.parent().clone());
        $self.remove();
      });
  </script>
  </head>
  <body>
    <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>
  </body>
</html>
Was it helpful?

Solution

First add jquery in your code and use on() in place of live().

Also write your code in $(function(){...}) so, that your code will work after document ready

<script src="http:/code.jquery.com/jquery-1.9.1.js"></script>
<script>
   $(function () {
       $(".repeat").on('click', function () {
          var $self = $(this);
          $self.after($self.parent().clone());
          $self.remove();
       });
   });
</script>

Working Demo

Updated, if you want it to work for more inputs then try this,

$(function () {
    $(".repeat").on('click', function (e) {
        e.preventDefault();// to prevent form submit
        var $self = $(this);
        $self.before($self.prev('table').clone());// use prev() not parent()
        //$self.remove();// remove this line so you can add more inputs
    });
});

Updated Demo

OTHER TIPS

The $(".repeat") construction says that jQuery must be used. Try to add <script type="text/javascript" src="http://code.jquery.com/jquery-1.10.2.min.js"></script> before your <script>

Try this

HTML

<body>
    <form>
        <div class="parent">
      <div class="repeatable">
        <table border="1">
        <tr><td><input type="text" name="userInput[]"></td></tr></table>
        <button class="repeat">Add Another</button>
      </div>
      </div>
    <input type="submit" value="Submit">
    </form>
  </body>

Jquery

$(document).on('click', '.repeat', function (e) {
    e.preventDefault();
    $('.repeatable').parent('div.parent').append($('.parent').children('div:first').html());
});

See jsfiddle,

use

$(document).on('click', '.repeat', function () {

instead of

$(".repeat").live('click', function () {
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top