By 05/02/2014 5 Comments

How to move selected items up or down in Javascript

Move selected items up and down in listbox

  • We can move items up and down in a listbox

Following example describes how to move selected items up and down using javascript

<script>

function listbox_move(listID, direction) { // function pass 2 parameters, first the Id of source listbox which contains items to be moved up and down, second parameter defines the direction "up or down" as a string value

var listbox = document.getElementById(listID); // get listbox by an id

var selIndex = listbox.selectedIndex; // assign current selected index of listbox

if(-1 == selIndex) { // condition check,if user does not select any option inside listbox
alert("Please select an option to move.");  // display alert message
return;
}

var increment = -1; // assign -1 to increment variable

if(direction == 'up') // check condition if given direction is up

increment = -1;

else

increment = 1;

if((selIndex + increment) < 0 ||
(selIndex + increment) > (listbox.options.length-1)) {
return;
}

var selValue = listbox.options[selIndex].value;
var selText = listbox.options[selIndex].text;
listbox.options[selIndex].value = listbox.options[selIndex + increment].value
listbox.options[selIndex].text = listbox.options[selIndex + increment].text

listbox.options[selIndex + increment].value = selValue;
listbox.options[selIndex + increment].text = selText;

listbox.selectedIndex = selIndex + increment;
}

</script>

<select multiple="multiple" id = "listID"> <!--- listbox control rendered --->
<option value = "java">Java</option>
<option value = "php">Php</option>
<option value = "asp">Asp.net</option>
<option value = "boot">Bootstraps</option>
<option value = "r">Ruby</option>
<option value = "f">Facebook</option>
<option value = "g">Google</option>
<option value = "c">Css</option>
</select>

<br>

<!--- above function called by the following buttons --->

<button onclick="listbox_move('listID', 'up')"> Up </button>
<button onclick="listbox_move('listID', 'down')"> Down </button>






Posted in: JavaScript

Leave your valuable Comment

Have a natural attraction for women cosmetics and replica watches uk clothes, no
more than two for men the most attractive one, is to make their own driving experience, happy and can serve as the facade of the car, another is to highlight the taste edify sentiment rolex replica watch. The replica rolex is undoubtedly the most fashionable accessories, wear a suit to attend the activities, but also get a decent match on the replica watches .