Add, Remove, Modify OPTIONS

[Total: 0    Average: 0/5]

This shows a little example on how to use javascript to modify the content of a form list box.

Body Code:

<form name=exf1>
<select name="t1" size=4>
    <option value="1">ONE
    <option value="2">TWO
    <option value="3">THREE
</select><BR>
ADD: <input type=button value="Zero" onclick="addItem(0)">&nbsp;
     <input type=button value="Four" onclick="addItem(4)"><BR>
MODIFY: <input type=button value="One->enO" onclick="modifyItem()"><BR>
REMOVE: <input type=button value="Three" onclick="removeItem()"><BR>
</form>
<script>
function removeItem() {
  var _a;
  // this logic detects if the "zero" was already added or not
  if (document.exf1.t1[2].text=="THREE") _a = 2; else _a = 3;
  if (document.all)
    document.exf1.t1.options.remove(_a);
  if (document.layers)
    document.exf1.t1.options[_a] = null;
}
function modifyItem() {
  var _a;
  // this logic detects if the "zero" was already added or not.
  if (document.exf1.t1[0].text=="ONE") _a = 0; else _a = 1;
  document.exf1.t1[_a].text="enO";
}
function addItem(_n) {
  if (_n=="4") {_a = "FOUR"; _b = "4"; _c = document.exf1.t1.length; }
  if (_n=="0") {_a = "ZERO"; _b = "0"; _c = 0;}
  if (document.all) {
    var _t = document.createElement("OPTION");
        _t.text  = _a;
        _t.value = _b;
    document.exf1.t1.options.add(_t,_c);
  }
  if (document.layers) {
	for (var _j = document.exf1.t1.options.length; _j > _c; _j--)
	  document.exf1.t1.options[_j] = document.exf1.t1.options[_j-1];
	  
    document.exf1.t1.options[_c] = new Option(_a,_b,false,false);
  }
}
</script>

Times Viewed: 1

Leave a Reply

Your email address will not be published. Required fields are marked *