Bruno Monteiro
Bruno Monteiro

Reputation: 712

How to check if element already exists on list

I have the following JS file:

;(function ($) {    
    $('.filter-opts .opt').click(function(){
        var selectedName = $(this).html();
        $('.append').append('<li>' + selectedName + '</li>');
    });

    $(document).on('click', '.append li', function(){
        $(this).remove();
    });
})(jQuery);

Codepen: http://codepen.io/brunomonteiro3/pen/vGdJVR

As you can see, when a <li> option is clicked, it clone the element to another list. But I want to make sure if an item is already listed, it will not be listed again.

What would be the best option to verify it?

Upvotes: 0

Views: 3061

Answers (3)

rrk
rrk

Reputation: 15846

Check if the item already exists using filter funcition.

exist = $('.append li').filter(function() {
  return $(this).text() == selectedName
});
if (!exist.length)
  $('.append').append('<li>' + selectedName + '</li>');

DEMO

Upvotes: 2

D&#225;vid Horv&#225;th
D&#225;vid Horv&#225;th

Reputation: 4320

You should add a class or other identity attribute to each different item, and search for it:

$(function(){
    var $target = $(".append").first();
    $('.filter-opts .opt').click(function(){
        var name = $(this).attr("data-name");
        if ($target.find('[data-name="' + name + '"]').size() == 0) {
            $(this).clone().appendTo($target);
        }
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<ul class="filter-opts">
  <li class="opt" data-name="o1">Option 1</li>
  <li class="opt" data-name="o2">Option 2</li>
  <li class="opt" data-name="o3">Option 3</li>
  <li class="opt" data-name="o4">Option 4</li>
</ul>

<h2>Appended:</h2>

<ul class="append">
</ul>


If you can not change your HTML, you can track already added items, for example:

$(function(){
    var $target = $(".append").first();
    $('.filter-opts .opt').click(function(){
        if (!$(this).prop("alreadyAdded")) {
            $(this).clone().appendTo($target);
            $(this).prop("alreadyAdded", true);
        }
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<ul class="filter-opts">
  <li class="opt">Option 1</li>
  <li class="opt">Option 2</li>
  <li class="opt">Option 3</li>
  <li class="opt">Option 4</li>
</ul>

<h2>Appended:</h2>

<ul class="append">
</ul>

Upvotes: 1

laruiss
laruiss

Reputation: 3816

Here is one solution:

(function($) {
  var $secondList = $('.append');
  $('.filter-opts .opt').click(function() {
    var selectedName = $(this).text();
    if (!$secondList.find('li:contains("' + selectedName + '")').length) {
      $secondList.append('<li>' + selectedName + '</li>');
    }
  });

  $(document).on('click', '.append li', function() {
    $(this).remove();
  });
})(jQuery);

Codepen demo

Upvotes: 0

Related Questions