Using JScript in DHTML to Manipulate Objects in a SELECT tag
The following code can be used to dynamically add, remove or select all items in a SELECT object. The code assumes that when objects are added to the SELECT object, that the display text and value are identical.
<script language="javascript">
function addToList(txtBox, selectBox){
var oOption = document.createElement("OPTION");
oOption.text = txtBox.value;
oOption.value = txtBox.value;
selectBox.add(oOption);
txtBox.value = "";
txtBox.focus();
}
function removeFromList(selectBox){
selectBox.remove(selectBox.selectedIndex);
}
function selectEntireList(selectBox){
var fromObj = selectBox;
for ( selIndex = fromObj.length; selIndex -- ; selIndex > 0 ){
if(fromObj.options[selIndex].text != ""){
fromObj.options[selIndex].selected = true;
}
}
}
</script>
Comments
- Anonymous
March 05, 2005
After spending 10 minutes on analysing the for loop in selectEntireList I have to admit it is pure zen: iterating throught the options bottom-to-top without a var si = sel.options.length - 1 as initial index by swapping the for's increment (decrement here) and test are just masterly done. Placing the selIndex > 0 test in the increments place for documentional reasons is ingenious :D
I really like this loop.
-- b.gr
PS: to add something more serious to this comment: a few tests on dynamically adding options to selects can be found at http://xkr.us/js/dynsel