Reputation: 29
I'm trying to remove the appended elements one by one using javascript. I know how to remove the whole list but I want to remove the appended one by one on every time when I click on remove button which I don't know how to solve it till now.
here is a quick demo of what's happening when I click remove button:-
javascript code:-
$(window).on('pageinit', function() {
$(document).ready(function(){
$("#Sadd").click(function() {
var lastId = $("#modules h1").length;
var $newLabel = $("#module-1-label").clone();
var $newSc = $("#module-1-scredit").clone();
var $newSgrade = $("#module-1-sgrade").clone();
$newLabel.html("<h1>Module " + (lastId+1) + ":</h1>");
$newSc.find("label").attr("for", "Sc"+(lastId+1));
$newSc.find("input").attr("name", "Sc"+(lastId+1)).attr("id", "Sc"+(lastId+1));
$newSgrade.find("label").attr("for", "Sgrade"+(lastId+1));
$newSgrade.find("select").attr("name", "Sgrade"+(lastId+1)).attr("id", "Sgrade"+(lastId+1));
$("#modules").append($newLabel, $newSc, $newSgrade);
$("#Sremove").click(function() {
$("#module-1-label").last().remove()
$("#module-1-scredit").last().remove()
$("#module-1-sgrade").last().remove()
});
});
});
});
Update:- I'm able to remove items that were appended but that includes Module 1 and it's removing in reverse order
e.g:- 8 modules (1,2,3, etc) it will remove first 1 and 6 then it will remove 7 then 8
Upvotes: 0
Views: 218
Reputation: 32182
Hi Shihab Now used to this Jquery code
.last() and .closest() jquery code
$("#Sremove").click(function() {
var lastLi = $("#modules li").last();
var lastLi2 = lastLi.closest();
var lastLi3 = lastLi2.closest();
lastLi.remove();
lastLi2.remove();
lastLi3.remove();
});
Upvotes: 0
Reputation: 825
You bind the click event for remove module button, every time add the module. So please bind the click event once.
Use below code.
$(document).ready(function(){
$("#Sadd").click(function() {
var lastId = $("#modules h1").length;
var $newLabel = $("#module-1-label").clone();
var $newSc = $("#module-1-scredit").clone();
var $newSgrade = $("#module-1-sgrade").clone();
$newLabel.html("<h1>Module " + (lastId+1) + ":</h1>");
$newSc.find("label").attr("for", "Sc"+(lastId+1));
$newSc.find("input").attr("name", "Sc"+(lastId+1)).attr("id", "Sc"+(lastId+1));
$newSgrade.find("label").attr("for", "Sgrade"+(lastId+1));
$newSgrade.find("select").attr("name", "Sgrade"+(lastId+1)).attr("id", "Sgrade"+(lastId+1));
$("#modules").append($newLabel, $newSc, $newSgrade);
});
$("#Sremove").click(function() {
var lastId = $("#modules h1").length;
if(lastId > 5){
var lastLi = $("#modules h1").last().closest("li");
var lastLi2 = lastLi.next("li");
var lastLi3 = lastLi2.next("li");
lastLi.remove();
lastLi2.remove();
lastLi3.remove();
}
});
});
Hope this will help you.
Upvotes: 1