Reputation: 57
So here's my idea:
<select id="Main_body">
<option value="1">Alpha</option>
<option value="2">Beta</option>
</select>
<select id="Sub1">
<option value="11">Omega</option>
<option value="12">Gamma</option>
</select>
<select id="Sub2">
<option value="21">Foxtrot</option>
<option value="22">Kilo</option>
</select>
If I select "Alpha" in the "Main_Body" option, then I will get the choices of the "Sub1" category. If I select "Beta" then "Sub2" options will show.
Is there any way to do this in javascript? If so, please help me. Thank you everyone
Upvotes: 0
Views: 91
Reputation: 26
I will use the display: because the visibility is only hidden. You can look at JSFiddle:http://jsfiddle.net/anyuc7/sjyuo685/1/
var sub1=document.getElementById("Sub1"),
sub2=document.getElementById("Sub2"),
Main_body = document.getElementById("Main_body");
sub2.style.display = 'none';
Main_body.onchange = function (){
if(this.value == 1){
sub2.style.display = 'none';
sub1.style.display = 'inline-block';
}else{
sub1.style.display = 'none';
sub2.style.display = 'inline-block';
}
};
Upvotes: 0
Reputation: 4038
Change the visibility of your select element according to the selected option.
javaScript :
document.getElementById("Sub2").style.visibility = 'hidden';
var mainDDL = document.getElementById("Main_body");
mainDDL.onchange = function(){
// first hide both select element
document.getElementById("Sub1").style.visibility = 'hidden';
document.getElementById("Sub2").style.visibility = 'hidden';
// check the currently selected options value and make the matched valued element visible
if(this.value == 1){
document.getElementById("Sub1").style.visibility = 'visible';
}
else{
document.getElementById("Sub2").style.visibility = 'visible';
}
};
you can also retrieve the text of the selected option and show/hide the required select element accordingly. In that case replace the if-else block with the code below,
// get the selected options text
var selectedOption = this.options[this.value - 1].text;
// show/hide select element according to the match with the selected option
if(selectedOption == "Alpha"){
document.getElementById("Sub1").style.visibility = 'visible';
}
else{
document.getElementById("Sub2").style.visibility = 'visible';
}
Upvotes: 1