Işık Işık - 3 months ago 9
Javascript Question

Conditionally append clicked element to another element

I want to add an event listener to my unordered list elements with jQuery. When one of the list elements are clicked another unordered list is checked whether it has the clicked element from the former list, more correctly the clone of it, a list element with same text. If the latter list has it nothing happens, however if it does not have it, a copy of it is added to this latter unordered list.

I try to achieve it with

each()
but cannot manage to success the conditional
append()
and the case of starting with an empty
selecteds
list.

I need the latter list,
selecteds
, be empty once.

How can this be achieved?



$("ul#list li").on("click", function(event) {
var t = $(event.target).text();

if ($("ul#selecteds li").length == 0) {
$("ul#selecteds").append("<li></li>");
}

$("ul#selecteds li").each(function(index) {
var s = $(this).text();
if (s !== t) {
console.log("he");
$(event.target).clone().appendTo($("ul#selecteds"));
}
});
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<ul id="selecteds">
</ul>
<ul id="list">
<li>asdf</li>
<li>qwer</li>
<li>zxcv</li>
</ul>




Answer

You have the right idea, but you can't add a clone every time an element in the "selected" list doesn't match.

Also, you don't need to say e.g. ul#selecteds - ids are unique, and sufficient on their own.

$("#list li").on("click", function(event) {
  var t = $(this).text();   // the clicked text

  var exists = false;  // is it already selected?

  $('#selecteds li').each(function() {
    if ($(this).text() == t) {
      exists = true;   // found a match   
      return false;    // stop looking
    }
  });

  // no match? add one
  if (! exists) {
    $('<li>').text(t).appendTo('#selecteds');
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<ul id="selecteds">
</ul>
<ul id="list">
  <li>asdf</li>
  <li>qwer</li>
  <li>zxcv</li>
</ul>