I wish to display options in a select on the basis of what was selected in previous select, I have tried using createOption in javascript, but it keeps on creating options as many times as I change the option in parent select, hence I need a way to accomplish that, my code is as follow:
function addsem(deg)
{
var semnum,i;
switch(deg)
{
case 'var1':numsem=8;
break;
case 'var2':numsem=6;
break;
case 'var3':numsem=10;
break;
case 'var4':numsem=4;
}
select1=document.getElementById('selsem');
var sem=new Array('I','II','III','IV','V','VI','VII','VIII','IX','X');
for(i=0;i<numsem;i++)
{
var opt = new Option(sem[i],sem[i]);
select.options.add(opt);
}
}
my html code:
<select name="seldeg" id="seldeg" style="width:180px onChange="addsem(this.value);">
<option value="deg">Select</option>
<option value="var1">var1</option>
<option value="var2">var2</option>
<option value="var3">var3</option>
<option value="var4">var4</option>
</select>
<select name="selsem" id="selsem" style="width:180px;" onchange="" >
<option value="sem">Select</option>
</select>
I wish select to show different range of sems ie I,II...IV for var4, I,II....VI for var2
everytime I change deg value.
Thaknyou in advance
In your Javacript, select.options.add
should be select1.options.add
. There's a syntax error in the HTML, you didn't close your style="width:180px
attribute. Also you need to remove the items from the select so that you don't get duplicate items each time you change the first select.
function addsem(deg) {
var semnum, i;
switch (deg) {
case 'var1':
numsem = 8;
break;
case 'var2':
numsem = 6;
break;
case 'var3':
numsem = 10;
break;
case 'var4':
numsem = 4;
}
select1 = document.getElementById('selsem');
// remove existing items
while (select1.options.length) {
select1.remove(0);
}
var sem = new Array('I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX', 'X');
for (i = 0; i < numsem; i++) {
var opt = new Option(sem[i], sem[i]);
select1.options.add(opt); // changed to select1
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.