Adding jQuery HTML?

I am trying to add link text inside <li>to <ul>. The problem is that he is trying to scan and find duplicates, not add a new one

.

Here is the code:

$('.popular-list li a').live("click",function() //this will apply to all anchor tags
        { 
                var stuff = $(this).text();
                var match = $('#favoritesdrinks li:contains(' + stuff + ')');


                if(match) {
                        alert("Already Added")
                } else {
                        $('#favoritesdrinks').append('<li>'+stuff+'</li>');


                }


        }
);

UPDATE IS THE WORKING CODE:

 $('.popular-list li a').live("click",function() //this will apply to all anchor tags
        { 
                var $stuff = $(this).text();
                var hasDuplicate = false;

      $('#favoritesdrinks li').each( function(){
       if ($(this).text() === $stuff ){
          hasDuplicate = true;
          return false;
       }
    });

    if (hasDuplicate ) {
       alert("Already Added") } 
    else {         
       $('#favoritesdrinks').append('<li>'+$stuff+'</li>'); 
    }
});
+3
source share
3 answers

you will need every li element. Then do the comparison, and if you have a match, you can set var to true, and then break out of each of them using return false so you don't keep repeating when you already know the result.

 $('.popular-list li a').click(function() { 

    var $stuff = $(this).text();
    var hasDuplicate = false;

    $('#favoritesdrinks li').each( function(){
       if ( $(this).text() === $stuff ){
          hasDuplicate = true;
          return false;
       }
    });

    if (hasDuplicate ) {
       alert("Already Added") } 
    else {         
       $('#favoritesdrinks').append('<li>'+$stuff+'</li>'); 
    }

  });
+3
source

$('#favoritesdrinks li').text() . text() ( each()) (, found), .

+2

I think the reason it only works on the first is related to your selector:

var $inside = $('#favoritesdrinks li').text();

This will match all <li> tags, so when you add more items to your list, your comparison will not work. You may have more luck using the contains selector :

var match = $('#favoritesdrinks li:contains(' + $stuff + ')');

if (match) {
    alert('Already added');
}
...
+1
source

Source: https://habr.com/ru/post/1714551/


All Articles