Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using jQuery's .add method

Tags:

jquery

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.

like image 748
sharat87 Avatar asked Jun 19 '11 12:06

sharat87


People also ask

What is the difference between remove () and empty () methods?

remove() – Removes all child elements with selected element. In this method you can restore all data but not event handlers of removed elements from the DOM. All data and events related with elements will be removed. empty() – Removes all content and child elements from the selected element.

How can add Li in UL dynamically using jQuery?

Answer: Use the jQuery append() Method You can simply use the jQuery append() method to add <li> elements in an existing <ul> element. The following example will add a <li> element at the end of an <ul> on click of the button.

How do you replace an element with another in jQuery?

We can replace HTML elements using the jQuery . replaceWith() method. With the jQuery replaceWith() method, we can replace each element in the set of matched elements with the provided new content and return the set of elements that were removed.

How can create DOM element in jQuery?

Answer: Use the jQuery append() or prepend() method You can add or insert elements to DOM using the jQuery append() or prepend() methods. The jQuery append() method insert content to end of matched elements, whereas the prepend() method insert content to the beginning of matched elements.


1 Answers

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

like image 108
Matt Ball Avatar answered Oct 06 '22 01:10

Matt Ball