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>');
}
});
-
You probably shouldn't update your code to the working code, as other people who come in search of an answer to similar questions will want to see why the question was originally asked and now they can't do that. Plus the working code is in the accepted answer itself!Adam Batkin– Adam Batkin2009年08月06日 20:25:30 +00:00Commented Aug 6, 2009 at 20:25
3 Answers 3
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>');
}
});
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.
Comments
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');
}
...