8

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:

  1. Click the first element to select it.
  2. Ctrl-click the second element to select it too.
  3. Then click the third element (without 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.

4
  • i think you should do prevSelections.each(...) to remove classes Commented Jun 19, 2011 at 13:02
  • 1
    @venimus there is no need to use .each() for that prevSelections.removeClass('foo') would suffice. Commented Jun 19, 2011 at 13:04
  • @venimus, Actually, jQuery methods act on all selected elements in its object set, so .each isn't necessary Commented Jun 19, 2011 at 13:04
  • it was just a first thought, but +1 for the simple implementation Commented Jun 19, 2011 at 13:09

2 Answers 2

3

.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/

Sign up to request clarification or add additional context in comments.

3 Comments

what do you mean, do you get an error? I don't have a mac, could you give more info?
Of course - my apologies. On Macs, ctrl-click is the same thing as right-click. So, instead of ctrl-click selecting additional items in the list, it just shows the context menu.
Oh! That's a very important piece of information for non-mac web devs like me. Thanks a ton for sharing. I'll research deeper :)
1

add constructs a new jQuery node set object.

Instead of

prevSelections.add($(this).toggleClass('selected');

do

prevSelections = prevSelections.add($(this).toggleClass('selected');

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.