Reputation: 7526
Either I am making a very silly mistake here, or there is a bug with jQuery's .add
method. Most likely the former.
I am trying to implement a list of items that could be selected. Here's my code on jsfiddle.
The test case that is failing is the following:
Ctrl
).Now, I'd expect the first and second to be de-selected, I believe the implementation also does this. But the second one does not get de-selected.
Digging a little, it seems that the .add
is actually not adding my elements to the jQuery object set and for the life of me, I can't figure out why.
Any suggestions on this? Or is this not the way the .add
method is supposed to be used?
Edit: I know jquery-ui has a control for this kind of thing, but I have already evaluated it and it does not work for me. Thanks.
Upvotes: 8
Views: 218
Reputation: 359796
.add
returns a new jQuery object, so you need to grab the value returned.
prevSelections = prevSelections.add(...);
Here's some other cleanup applied:
var ps = $(),
clazz = 'selected';
$('#list').delegate('li', 'click', function(e) {
if (e.ctrlKey) {
ps = ps.add($(this).toggleClass(clazz));
} else {
if (ps.length) {
ps.removeClass(clazz);
}
ps = $(this).addClass(clazz);
}
});
Demo: http://jsfiddle.net/mattball/mAPQA/
Upvotes: 3