You need to track some kind of index, I think in your case you can use value for each option. (but you can use the highlighted data-* attribute if you need to)
Using this value, you can search the current list and see where it should fit. Complete the parameters and verify that the value is greater than the one you are moving. If you find it, then insert it before that, if you do not succeed, then insert it at the end.
This should do it:
$("#button2").click(function(){ $("#list2 > option:selected").each(function(){ var item = $(this).remove(); var match = null; $("#list1").find("option").each(function(){ if($(this).attr("value") > item.attr("value")){ match = $(this); return false; } }); if(match) item.insertBefore(match); else $("#list1").append(item); }); });
You can apply the same thing to the opposite.
Here is a working example
source share