Move <option> to top of list with Javascript
I'm trying to create a b开发者_如何学运维utton that will move the currently selected OPTION in a SELECT MULTIPLE list to the top of that list. I currently have OptionTransfer.js implemented, which is allowing me to move items up and down the list. I want to add a new function
function moveOptionTop(obj){ var i = obj.selectedIndex; if(i == 0){return;} var length = obj.options.length; for(j=length;j>0;j++){ obj.options[j] = obj.options[j-1]; //move all elements up a position to free up index 0 } obj.options[0] = obj.options[i+1]; //set new [0] element for(j=i+1;j
Use DOM manipulation methods. Given:
var select = document.getElementById ("..."); // select element
var option = select.options[select.selectedIndex] // option element
- Remove selected option from select:
select.removeChild (option)
- Reinsert it as first child:
select.insertChild (option, select.firstChild)
Or use select.add() and select.remove()
http://www.w3schools.com/jsref/dom_obj_select.asp
精彩评论