Sb Racket Sb Racket - 5 months ago 14
jQuery Question

Display div based on option selected in javascript

I have 3 options here

<select id="adtype" name="adtype" onchange="validate();">
<option id="banner" value="ban">Banner Advertisement</option>
<option id="textr" value="txt">Text Advertisement</option>
<option id="log" value="log">Login Advertisement</option>
</select>


I need to display 3 divisions, 1 division per option when each option is selected
suppose when banner is selected,banner division is displayed
but all the divisions must be in same position in the page .
My javascript code is:

<script>
function validate()
{
var ddl = document.getElementById("adtype");
var selectedValue = ddl.options[ddl.selectedIndex].value;
if (selectedValue == "selectoption")
{
alert("Please select an Advert type");
}
if(selectedValue == "txt")
{
document.getElementById("ban").style.display="none";
document.getElementById("textadvert").style.display="block";
}
}
</script>`


My javascript code is not doing the work please anyone can make it posible.

Answer

I've made this codepen for you which does not require a new if for every div you got (useful if you want to add more)

HTML difference: "display-ban" ID instead of just "ban" because you had a conflict on the "log" ID, and this one might be more specific.

<div class="hidden" id="display-ban">BAN DIV</div>

JS main difference:

var subjectDiv=document.getElementById("display-"+selectedValue)
subjectDiv.style.display="block";

Also I made a check for the previously displayed item, and hide it.

if(prev){
 prev.style.display="none";
}

Hope this helps. You can find the codepen here.