The examples in this article describe the way that JavaScript controls how items move up and down in the ListBox list box. Share to everyone for your reference. The specific analysis is as follows:
This JS code can control the elements within the listbox to move up or down, this function is very useful. The following is a detailed code
Copy Code code as follows:
function Listbox_move (Listid, direction) {
var listbox = document.getElementById (Listid);
var selindex = Listbox.selectedindex;
if ( -1 = Selindex) {
Alert ("Please select a option to move.");
Return
}
var increment =-1;
if (direction = ' 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;
}
//..
//..
Listbox_move (' countrylist ', ' up '); Move up the selected option
Listbox_move (' countrylist ', ' down '); Move Down the selected option
The following is a detailed demo code that you can use in the browser
Copy Code code as follows:
Click below buttons to select or deselect all options from select Box.<br>
<select id= "Lsbox" name= "Lsbox" "size=" "multiple=" ">
<option value= "1" >India</option>
<option value= "2" >united states</option>
<option value= "3" >China</option>
<option value= "4" >Italy</option>
<option value= "5" >Germany</option>
<option value= "6" >Canada</option>
<option value= "7" >France</option>
<option value= "8" >united kingdom</option>
</select> <br>
<button onclick= "Listboxmove (' Lsbox ', ' up ');" >move up</button>
<button onclick= "Listboxmove (' Lsbox ', ' Down ');" >move down</button>
<script>
function Listboxmove (Listid, direction) {
var listbox = document.getElementById (Listid);
var selindex = Listbox.selectedindex;
if ( -1 = Selindex) {
Alert ("Please select a option to move.");
Return
}
var increment =-1;
if (direction = ' 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>
I hope this article will help you with your JavaScript programming.