Reputation: 155
I'm trying to make some div's with jquery
that by clicking on them I can add their text into a list and by clicking again on that div I can remove just that div's text from the list, not all of them.
but when I order to remove by clicking again on that div all text remove's from list
$(".first-div").on('click', function() {
$(this).toggleClass("div2 active");
let matn = $("<h3>" + $(this).html() + "</h3>");
if ($(this).hasClass("active")) {
$(".textbox").append(matn);
} else {
$(".textbox").children("h5").html($(this).html()).remove();
}
})
body {
padding: 3em;
}
.first-div {
padding: 0.5em 1.5em;
background-color: silver;
margin: 2em 0;
border: 2px solid silver;
}
.div2 {
border-color: red;
}
.text {
margin-top: 3em;
padding: 1em;
}
.textbox {
padding: 1.5em;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<section>
<div class="first-div">
<h5>text1</h5>
</div>
<div class="first-div">
<h5>text2</h5>
</div>
<div class="first-div">
<h5>text3</h5>
</div>
</section>
<section class="text">
<div class="textbox"></div>
</section>
</body>
Upvotes: 4
Views: 68
Reputation: 8366
You can just find the element that contains the text and remove it from the list like this:
$(".first-div").on('click', function() {
$(this).toggleClass("div2 active");
let matn = $("<h3>" + $(this).html() + "</h3>");
if ($(this).hasClass("active")) {
$(".textbox").append(matn);
} else {
$(".textbox").find("h5:contains(" + $(this).text().trim() + ")").remove();
}
})
In your code just change this:
$(".textbox").children("h5").html($(this).html()).remove();
to this:
$(".textbox").find("h5:contains(" + $(this).text().trim() + ")").remove();
Upvotes: 1
Reputation: 337560
A simpler pattern to follow is to build the entire list everytime a change is made, instead of having to maintain the array when an item is selected/deselected.
Also note that your current example is nesting <h5>
elements within <h3>
, which is invalid.
$(".first-div").on('click', function() {
$(this).toggleClass("div2 active");
let matn = $('.first-div.active').map(function() {
return $(this).html();
}).get();
$(".textbox").html(matn);
})
body {
padding: 3em;
}
.first-div {
padding: 0.5em 1.5em;
background-color: silver;
margin: 2em 0;
border: 2px solid silver;
}
.div2 {
border-color: red;
}
.text {
margin-top: 3em;
padding: 1em;
}
.textbox {
padding: 1.5em;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<section>
<div class="first-div">
<h5>text1</h5>
</div>
<div class="first-div">
<h5>text2</h5>
</div>
<div class="first-div">
<h5>text3</h5>
</div>
</section>
<section class="text">
<div class="textbox"></div>
</section>
Upvotes: 1