how can clear all options and optgroup of select and setting new optgroup and options?


HI
 
         THe form having an select field. I wants to clear all optgroup and existing options and set new optgroup and options to the existing select field. Can i do this changes through javascript?

Thanks.
b_rajathilagamAsked:
Who is Participating?
 
ZvonkoConnect With a Mentor Systems architectCommented:
Here my method:

<html>
<head>
<script>
function chngSel(theBtn){
  theSel = theBtn.form.mySel;
  newSel = document.createElement("select");
  opt = newSel.options;
  newSel.id = "mySel";
  newGrp = document.createElement("optgroup");
  newGrp.setAttribute("label", "new Label 1");
  newGrp.appendChild(new Option());
  newGrp.appendChild(new Option());
  newSel.appendChild(newGrp);
  newGrp = document.createElement("optgroup");
  newGrp.setAttribute("label", "new Label 2");
  newGrp.appendChild(new Option());
  newGrp.appendChild(new Option());
  newGrp.appendChild(new Option());
  newSel.appendChild(newGrp);
  theSel.parentNode.replaceChild(newSel, theSel);
  opt[0].text = "new Opt 1";
  opt[1].text = "new Opt 2";
  opt[2].text = "new Opt A";
  opt[3].text = "new Opt B";
  opt[4].text = "new Opt C";

}
</script>
</head>
<body>
<form>
<select name="mySel">
<optgroup label="Group 1">
<option>Item 1</option>
<option>Item 2</option>
<option disabled="true">Item 3</option>
<option>Item 4</option>
</optgroup>
<optgroup label="Group 2">
<option>Item A</option>
<option>Item B</option>
<option disabled="true">Item C</option>
<option>Item D</option>
</optgroup>
</select>
<input type=button value="Change" onClick="chngSel(this)">
</form>
</body>
</html>

0
 
BenMorelCommented:
Hi !

You can do this with var "options" from your select object, and "new Option()" to set a new one.

Here is a very easy example :

==========================================================

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>Test page</title>
<script language="javascript">
<!--
var NewMenu = new Array("New item 1", "New item 2", "And so on ..!");

function Change() {
 var s=document.f.MySelect;
 var i;
 // erase
 for (i=s.options.length-1; i>=0; i--) {
  s.options[i] = null;
 }
 for (i=0; i<NewMenu.length; i++) {
  s.options[i] = new Option(NewMenu[i]);
 }
}
//-->
</script>
</head>

<body>
<form name="f">
<select name="MySelect">
<option>Item 1</option>
<option>Item 2</option>
<option>...</option>
</select>
<input type="button" name="Submit" value="Change them !" onClick="Change()">
</form>
</body>
</html>

==========================================================

See ya ;)
Ben
0
 
ZvonkoSystems architectCommented:
Why the grading B???
0
All Courses

From novice to tech pro — start learning today.