Prady Prady - 5 months ago 8
jQuery Question

How to move item to top and bottom of selectlist using jquery

I am trying to set options to move to top or bottom of the list. Any thoughts on how to get this using jquery



$(document).ready(function() {
$('input[type="button"]').click(function() {
var $op = $('#select2 option:selected'),
$this = $(this);
if ($op.length) {
($this.val() == 'Up') ?
$op.first().prev().before($op):
$op.last().next().after($op);
}
});
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select multiple id="select2">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
<input type="button" value="Up">
<input type="button" value="Down">
<input type="button" value="Top">
<input type="button" value="Bottom">




Answer

$(document).ready(function() {
  $('input[type="button"]').click(function() {
    var $op = $('#select2 option:selected'),
      $this = $(this);
    console.log($this.val())
    if ($op.length) {
      if ($this.val() == 'Top') {
        $('#select2').prepend($op)
      }else if ($this.val() == 'Bottom') {
        $('#select2').append($op)
      }else if ($this.val() == 'Up') {
       $op.prev().before($op);
      }else if ($this.val() == 'Down') {
        $op.next().after($op);
      }

    }
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select multiple id="select2">
  <option value="1">1</option>
  <option value="2">2</option>
  <option value="3">3</option>
  <option value="4">4</option>
</select>
<input type="button" value="Up">
<input type="button" value="Down">
<input type="button" value="Top">
<input type="button" value="Bottom">

Use .prepend() to move top

Description: Insert content, specified by the parameter, to the beginning of each element in the set of matched elements.

Use .append() to move bottom

Description: Insert content, specified by the parameter, to the end of each element in the set of matched elements.