I have 2 drop downs, this thing here is when user select BMW i want to fill data 1,2,3,4,5 & when he selects Volvo i want to display 5,6,7,8,9. Data is getting populated in second drop down but i can see old data as well & as many times i click the list is getting increased. I want to show only specific data on selection & data should also not get repeated. below is my approach.
<!DOCTYPE html>
<html>
<head>
<title></title>
<script type="text/javascript">
function myFunction() {
var x = document.getElementById("mySelect").value;
if(x=='BMW'){
var select = document.getElementById("participant");
var options = ["1", "2", "3", "4", "5"];
for(var i = 0; i < options.length; i++) {
var opt = options[i];
var el = document.createElement("option");
el.textContent = opt;
el.value = opt;
select.appendChild(el);
}
}
if(x=='Volvo'){
var select = document.getElementById("participant");
var options = ["6", "7", "8", "9", "10"];
console.log(options)
for(var i = 0; i < options.length; i++) {
var opt = options[i];
var el = document.createElement("option");
el.textContent = opt;
el.value = opt;
select.appendChild(el);
}
}
}
</script>
</head>
<body>
<select id="mySelect" onchange="myFunction()">
<option value="" disabled selected>Select Type</option>
<option value="BMW">BMW</option>
<option value="Volvo">Volvo</option>
</select>
<br><br>
<select id="participant">
<option>select</option>
</select>
</body>
</html>
You should change the innerHTML
of the <select>
before adding new <option>
.
function myFunction() {
var x = document.getElementById("mySelect").value;
var select = document.getElementById("participant");
//this line clears the old data.
select.innerHTML = '<option>Select</option>'
if(x=='BMW'){
var options = ["1", "2", "3", "4", "5"];
for(var i = 0; i < options.length; i++) {
var opt = options[i];
var el = document.createElement("option");
el.textContent = opt;
el.value = opt;
select.appendChild(el);
}
}
if(x=='Volvo'){
var options = ["6", "7", "8", "9", "10"];
console.log(options)
for(var i = 0; i < options.length; i++) {
var opt = options[i];
var el = document.createElement("option");
el.textContent = opt;
el.value = opt;
select.appendChild(el);
}
}
}
<select id="mySelect" onchange="myFunction()">
<option value="" disabled selected>Select Type</option>
<option value="BMW">BMW</option>
<option value="Volvo">Volvo</option>
</select>
<br><br>
<select id="participant">
<option>select</option>
</select>