Reputation: 74
I'm trying to show a list of items to another list by clicking it. The selected items are showing but only in a single line. I tried to add a break line but failed to do it.
I need to keep the items from list-select. It's like showing what I selected. The real scenario is selecting multiple products then show the selected product name
It needs to keep update the items from list-show if the customer remove the item from being selected.
$(".list-select li").on("click", function() {
$(this).toggleClass("selected");
if ($(this).hasClass("selected")) {
$(".list-show li").html($(".selected span").text() + "<br />");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="list-select">
<li> <span>item 1</span> </li>
<li> <span>item 2</span> </li>
<li> <span>item 3</span> </li>
</ul>
<ul class="list-show">
<li> </li>
</ul>
Upvotes: 1
Views: 742
Reputation: 780
Just try this simpler approach:
$(".list-select li").on("click", function() {
$(this).toggleClass("selected");
$(".list-show").html($(".list-select li.selected").clone());
});
Upvotes: 1
Reputation: 500
Instead of replacing the html of the show
list, you can append the clicked element instead.
For example:
$( ".list-select li" ).on( "click", function() {
$( ".list-show" ).append( this )
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
list-select:
<ul class="list-select">
<li> <span>item 1</span> </li>
<li> <span>item 2</span> </li>
<li> <span>item 3</span> </li>
</ul>
<div></div>
list-show:
<ul class="list-show">
</ul>
If you want to keep the original list, that can be done like this:
$( ".list-select li" ).on( "click", function() {
var clone = this.cloneNode(true);
$( ".list-show" ).append( clone )
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
list-select:
<ul class="list-select">
<li> <span>item 1</span> </li>
<li> <span>item 2</span> </li>
<li> <span>item 3</span> </li>
</ul>
<div></div>
list-show:
<ul class="list-show">
</ul>
Upvotes: 1
Reputation: 16384
You can add (actually clone and then append new elements to another place) via clone()
and append()
jQuery methods. It's necessary for adding elements to the next list. For removing them from the second list (let's imagine, that it should work by clicking an item in the first list), you can use li:contains(SPECIFIC_CONTENT_TO_MATCH)
to select the element, and then just remove()
it:
$(".list-select li").on("click", function() {
$(this).toggleClass("selected");
if ($(this).hasClass("selected")) {
$(".list-show").append($(this).clone());
} else {
$(`.list-show li:contains('${$(this).text()}')`).remove();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Select:
<ul class="list-select">
<li> <span>item 1</span> </li>
<li> <span>item 2</span> </li>
<li> <span>item 3</span> </li>
</ul>
Show:
<ul class="list-show"></ul>
Upvotes: 2