norbdum
norbdum

Reputation: 2491

jQuery sortable move up/down multiple <options> in <select>

I am trying to move the in using the following code but when i select multiple options it doesn't work right

How can I move multiple elements up and down?

<script type="text/javascript">  
  \$().ready(function() { 
//for moving elements up and down
\$('.up-button').click(function(){

 before = \$('#select2 option:selected').prev();
    \$('#select2 option:selected').insertBefore(before);
    });

\$('.down-button').click(function(){
   after = \$('#select2 option:selected').next();
    \$('#select2 option:selected').insertAfter(after);
}); 
   });  
 </script>

You can find the reference at JS live code

Upvotes: 0

Views: 4009

Answers (2)

R. Oosterholt
R. Oosterholt

Reputation: 8090

changed up/down logic a bit:

$('.up-button').click(function(){
  $('#select2 option:selected:first-child').prop("selected", false);
  before = $('#select2 option:selected:first').prev();
    $('#select2 option:selected').detach().insertBefore(before);

});

$('.down-button').click(function(){
  $('#select2 option:selected:last-child').prop("selected", false);
  after = $('#select2 option:selected:last').next();
    $('#select2 option:selected').detach().insertAfter(after);
}); 

fiddle

Upvotes: 1

dann
dann

Reputation: 853

use .first() and .last(), because you're selecting multiple elements

//for moving elements up and down
$('.up-button').click(function(){
 before = $('#select2 option:selected').first().prev();
    $('#select2 option:selected').insertBefore(before);

});

$('.down-button').click(function(){
   after = $('#select2 option:selected').last().next();
    $('#select2 option:selected').insertAfter(after);
}); 

Upvotes: 2

Related Questions