views:

26

answers:

4

Hi, I am having a problem appending list items from one ul to another. When each list item is clicked, it is supposed to be appended into another ul. However once those items are appended, they will continue to append themselves into their current ul....meaning they will sort themselves to the bottom of the list. For example:

<ul class="first-holder">
            <li><input type="checkbox" name="location1"  /> Location 1</li>
            <li><input type="checkbox" name="location2"  /> Location 2</li>
            <li><input type="checkbox" name="location3"  /> Location 3</li>
            <li><input type="checkbox" name="location4"  /> Location 4</li>
            <li><input type="checkbox" name="location5"  /> Location 5</li>


            </ul>


            <div class="more-options first-option">
            <ul>
            <li><input type="checkbox" name="location-6" checked="checked" /> Location 6</li>
            <li><input type="checkbox" name="location7" checked="checked" /> Location 7</li>
            <li><input type="checkbox" name="location8" checked="checked" /> Location 8</li>
            </ul>
            </div>

The jquery:

$('div.more-options li').click(function() {

                $(this).appendTo($('ul.first-holder'));
                return false;

           }); 

What happens is this: The list items in the div.more-options will append to ul.first-holder, but then when those items are in ul.first-holder, clicking them will cause them to append to the end of ul.first-holder. Once the li's have been appended to ul.first-holder they shouldn't move anywhere. I can't figure out how to make that happen.

A: 

Try removing event handler from the item. It will just stop receiving click events.

$(this).unbind('click');
$(this).appendTo($('ul.first-holder'));

http://api.jquery.com/unbind/

Nikita Rybak
yes, this did it. thanks.
johnnyb
A: 

That's because you are moving the node with the click event attached to it. So when that node is appended to the other ul, the click event still applies.

You can either copy the node and append that, or remove the click event when appending.

Peter Kruithof
A: 

Use .delegate() here instead, like this:

$('div.more-options').delegate('li', 'click', function() {
  $('ul.first-holder').append(this);
}); 

You can test it out here.

Currently your click handlers are on the <li> elements, and moving with them...instead put the click handler on the .more-options <div> itself, so there is no handler to move. This is also cheaper to execute if you have more than a few elements :)

Nick Craver
A: 

You want to only handle the first click event, like this:

$('div.more-options li').one('click', function() { ... }):
SLaks