javascript - Click to remove parent div -


i'm struggling seems pretty basic, though i'm not seeing doing wrong.

i want onclick div cloned till maximum of 4 times. (so far good), , want have remove button deletes 1 of divs inserted.

and problem right there. i can't remove button work.

js

$(document).ready(function() {   var max_fields      = 4; // maximum input boxes allowed   var wrapper         = $("#adddrivercontent div:first");    var add_button      = $(".add_field_button"); // add button id   var x = 0    $(add_button).click(function(e) {     e.preventdefault();     // max input box allowed     if(x < max_fields) {       x++;        $(wrapper).clone().append('<a href="#" class="remove_field">remove</a>').appendto($('#clone_wrapper'));}   });    // user click on remove text   $(wrapper).on("click",".remove_field", function(e) {     e.preventdefault();     $(this).parent().sibling('#content').remove();     x--;   })  }); 

html

<div id="adddrivercontent" style="display:none;">   <div id="content">     contents   </div> </div>  <button type="button" class="add_field_button" id="clone_button">add driver</button> <div id="clone_wrapper"></div> 

take @ my fiddle.

(i've started this example)

there 2 problems javascript

  1. you attaching click event handler wrong element. element attaching not visible on page , never clicked.
  2. your line try remove clicked content wrong. $(this).parent().remove() enough.

see updated fiddle

$(document).ready(function() {     var max_fields = 4; //maximum input boxes allowed     var wrapper = $("#adddrivercontent div:first");     var add_button = $(".add_field_button"); //add button id     var x = 0      $(add_button).click(function(e) {         e.preventdefault();         if (x < max_fields) { //max input box allowed             x++;             $(wrapper).clone().append('<a href="#" class="remove_field">remove</a>').appendto($('#clone_wrapper'));         }     });      $(document).on("click", ".remove_field", function(e) { //user click on remove text         e.preventdefault();         $(this).parent().remove();         x--;     }) }); 

Comments