Code Code - 1 year ago 103
Javascript Question

Hide and show divs according to dropdown selected

I have a dropdown list containing 7 options. Each option a user selects they have to fill out a description in a text area right below it. What I'm trying to achieve is when an option is selected show the appropriate div and hide the others. This is what I've got so far

$(document).ready(function () {
... hide the remaining divs here

$("#ProjectStatus").change(function () {
var selectedValue = "";
$("#ProjectStatus option:selected").each(function () {
selectedValue += $(this).val();
if (selectedValue === "Define (Labelling)") {
... More if statements here for the other divs

My questions is, is there a cleaner way to go about this? Because currently I have multiple
statements and hiding and show the appropriate divs is getting a little ugly.

Update following @Mairaj answer

function showDiv() {
var divID = $("#ProjectStatus option:selected").attr("data-div");
alert(divID); //this comes as undefined
$("#" + divID).show();
$("#" + divID).siblings().hide();

I've added two divs as:

<div class="form-group" id="Define (Labelling)" style="display: none;">
@Html.LabelFor(model => Model.LabellingInfo, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.TextAreaFor(model => Model.LabellingInfo, htmlAttributes: new { @class = "form-control description" })
<div class="form-group" id="Analysis (Root Cause)" style="display:none;">
@Html.LabelFor(model => Model.RootCauseInfo, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.TextAreaFor(model => Model.RootCauseInfo, htmlAttributes: new { @class = "form-control description" })

Answer Source

You can add a custom attribute(data-div) to each option of dropdown which will be ID of div which will be shown.

<div id="divMain" >
    <div id="Div1">Div1</div>
    <div id="Div2" style="display:none">Div2</div>
    <div  id="Div3" style="display:none">Div3</div>

<select id="ddlOption" onchange="showdiv()">
    <option value="Div1" data-div="Div1">Div1</option>
    <option value="Div2" data-div="Div2">Div2</option>

Here is jquery code which will show hide div according to the selected option

function showdiv()
   var divID = $("#ddlOption option:selected").attr("data-div");
   divID = divID.replace(" ","");
   $("div[id$='" + divID+"']").show();
   $("div[id$='" + divID + "']").siblings().hide();
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download