blazerix blazerix - 2 months ago 6
CSS Question

How do I delete dynamically created elements in javascript/jquery?

So I'm trying to figure out a way to delete dynamically created elements in my program. I can currently add a pattern above or below the current one.

What I am trying to do though, is to add a delete button right beside the two rows of squares, and then once the user clicks on that button, the particular pattern is removed and all other patterns move into proper positions.

What I have done so far:

var id_num = 1;
var picker = null;
$(function () {
$(document).on('click', ".repeat", function (e) {
e.preventDefault();
var $self = $(this);
var $parent = $self.parent();
if($self.hasClass("add-bottom")){
$parent.after($parent.clone(true).attr("id", "repeatable" + id_num));
id_num = id_num + 1;
//picker = null;

} else {
$parent.before($parent.clone(true).attr("id", "repeatable" + id_num));
id_num = id_num + 1;
//picker = null;
}
});
});


Any help or feedback is much appreciated!

Answer

You can add the delete button inside a container and use it to delete. Can be easy to move the button where you want.

http://codepen.io/anon/pen/QKgBzP

var id_num = 1;
var picker = null;
$(function () {
$(document).on('click', ".repeat", function (e) {
    e.preventDefault();
    var $self = $(this);
    var $parent = $self.parent();
    var newobj=$parent.clone(true).attr("id", "repeatable" + id_num);
    if($self.hasClass("add-bottom")){
      $parent.after(newobj);
      id_num = id_num + 1;
      //picker = null;

    } else {
      $parent.before(newobj);
      id_num = id_num + 1;
      //picker = null;
    }
    newobj.append("<button class=\"remove\"> Remove</remove>");
});   
$(document).on('click', ".remove", function (e) {
    $(this).parent().remove();
});
});
Comments