Reputation: 3476
I am trying to append the text of a link inside a <li>
to a <ul>
The problem is getting it to scan through and find duplicates and not add a new
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- THIS IS 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>');
}
});
Upvotes: 3
Views: 273
Reputation: 78667
you will need to each through the li items. Then do the compare and if you have a match you can set the var to true then break out of the each using return false so you dont keep iterating 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>');
}
});
Upvotes: 3
Reputation: 11056
I think the reason it only works on the first one is because of your selector:
var $inside = $('#favoritesdrinks li').text();
This will match all <li> tags, so when you have added more items to your list your comparison won't work. You might have more luck using the contains selector:
var match = $('#favoritesdrinks li:contains(' + $stuff + ')');
if (match) {
alert('Already added');
}
...
Upvotes: 1
Reputation: 52994
The $('#favoritesdrinks li').text()
retrieves the text of the first element matched only. Instead of calling text()
directly, try looping over the results (using each()
), and set some variable (like found
) if it finds the text.
Upvotes: 2