user6915755
user6915755

Reputation:

clone a div in display none mode

There is a NEWFORM button to add form when clicked. How to show the form when click on NEWFORM button. and then add divs. i wrote the below codes . but it's not working :

$(document).ready(function() {
  $(".newform").click(function() {
    $(".MyForm")
    .eq(0)
    .clone()
    .show()
    .insertAfter(".MyForm:last");
  });

  $(document).on('click', '.MyForm button[type=submit]', function(e) {
    e.preventDefault() // To make sure the form is not submitted 
    var $frm = $(this).closest('.MyForm');
    console.log($frm.serialize());
    $.ajax(
        $frm.attr('action'), 
        {
          method: $frm.attr('method'),
          data: $frm.serialize()
        }
    );
  });
});
.all{display:none;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.1/jquery.min.js"></script>
<span class="newform">NEWFORM+</span>
<div class="all">
  <form class="MyForm" method="post">
    <input type="text" placeholder="name" value="Aynaz" name="a1" />
    <select name="Avg">
      <option value="1">1</option>
      <option value="2">2</option>
    </select>
    <button type="submit">Submit</button>
  </form>
</div>

Upvotes: 0

Views: 1055

Answers (1)

Serg Chernata
Serg Chernata

Reputation: 12400

The problem is your css. You're making the entire wrapper div invisible. Thus, it hides everything inside of it even if you call .show().

$(document).ready(function() {
  $(".newform").click(function() {
    $(".MyForm")
    .eq(0)
    .clone()
    .insertAfter(".MyForm:last")
    .show();
  });

  $(document).on('click', '.MyForm button[type=submit]', function(e) {
    e.preventDefault() // To make sure the form is not submitted 
    var $frm = $(this).closest('.MyForm');
    console.log($frm.serialize());
    $.ajax(
        $frm.attr('action'), 
        {
          method: $frm.attr('method'),
          data: $frm.serialize()
        }
    );
  });
});
.all{display:none;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.1/jquery.min.js"></script>
<span class="newform">NEWFORM+</span>
<div>
  <form class="MyForm all" method="post">
    <input type="text" placeholder="name" value="Aynaz" name="a1" />
    <select name="Avg">
      <option value="1">1</option>
      <option value="2">2</option>
    </select>
    <button type="submit">Submit</button>
  </form>
</div>

Upvotes: 1

Related Questions