I am trying to add and remove <li>‘s to a <ul> using the data from within the class add-to-favourites, the problem is that when I have more than one word or a space between words the jQuery no longer recognises that it is the same word and adds the same value to the <ul> again.
You can see the problem here: http://jsfiddle.net/ZWxBb/
Try clicking on the rows of text you will see they are added and removed to the <ul> except for the first instance of class which is just added everytime it is clicked.
It would also be great if you could use more than 2 words as the element text, plus add a div which when clicked removed the item from favourites
HTML:
<div class="add-to-favourites">Two Words</div>
<div class="add-to-favourites">OneWords</div>
<div class="add-to-favourites">NoSpaces</div>
<ul id="favourites"></ul>
jQuery:
$(function () {
$('.add-to-favourites').click(function() {
var num = $(this).text();
var $fav = $('#favourites');
var $fav_li = $fav.find('.' + num + '_li');
if ($fav_li.length) {
$fav_li.remove();
} else {
$('#favourites').append('<li class="' + num + '_li">' + num + '</li>');
}
})
});
Thanks,
Ben
As lzzey said, class names cannot contain spaces. Try doing a .replace(” “, “_” ) on your class matching:
http://jsfiddle.net/ZWxBb/2/
UPDATE:
I would suggest using something other that the text to identify the li’s
Html:
Then js:
http://jsfiddle.net/ZWxBb/3/