tags:

views:

1574

answers:

3

Hi!

I have 2 listboxes and a button to add items from #list1 to #list2.

I also have a button to remove item from #list2 and add it again to #list1. But, when I remove the selected item, it goes to the end of the #list1.

Is there a way to make this removed item return to its original position?

Thanks!!

+1  A: 

If you have many items, going back to the original position will be tricky unless you store the original position relative to all other items (since you might remove other items from #list1).

To keep things simple you could instead provide an undo button that restored the most recently-moved item to its original position, by remembering either the previous or next elements in the list.

Store:

  1. $(item).prev() and $(item).next() of the most recently-moved item, and
  2. the removed item as removedItem.

Then depending on whether there's a prev() or after() defined for the original item, use something like:

$($(item).prev()).after(removedItem);

to restore the most recently-moved item to its original position.

Maciek
+1  A: 

Maybe thinking about ALL of the items in the listbox in a different way will help:

If the items in #list1 also exist in an array, and the items in #list2 also exist in an array: When you click the button...

  1. Find the item in the array that corresponds to #list1. Save it to a temporary variable and remember its position.
  2. Rebuild the first array in a for-loop, skipping over the selected item
  3. Rebuild the second array in a for-loop, when you get to the original position, insert the value stored in the temporary variable, and then conitinue to copy the rest of the second array items
  4. Remove ALL items from #list2
  5. Insert all of the items in the second array
Neil Fenwick
+1  A: 

I found a really good tutorial that covers this in video format, so instead of trying to debug your code I will point you to the vid!

I hope it helps :D

http://blog.themeforest.net/tutorials/jquery-for-absolute-beginners-day-5/

Dorjan
I watched the video, but it's not exacly what I'm looking for... but, thanks anyway! :-)
AndreMiranda