Search code examples
.netasp.net-mvcrazorc#-4.0

Hide a Drop-down list if an other drop-down list has a selected value


I have two drop-down lists, My task is to hide one of the drop-down lists. If the user chooses a value in drop-down list 1 I need to hide the drop-down list 2 and vice-versa.

 @if (Model.DeputyId == null)
                        {
                        <div class="form-group">
                            <label>@Html.DrawLabel("PoliticalGroup")</label>
                            @Html.DropDownListFor(m => m.PoliticalGroupId, Model.PoliticalGroups, @Html.DrawLabel("SelectAPoliticalGroup"), new { @class = "form-control" })
                        </div>
                        }
                        @if (Model.PoliticalGroupId == null)
                        {
                        <div class="form-group">
                            <label>@Html.DrawLabel("Deputy")</label>
                            @Html.DropDownListFor(m => m.DeputyId, Model.Deputies, @Html.DrawLabel("SelectADeputy"), new { @class = "form-control" })
                        </div>
                        }

These are the two drop-down lists that I need to control which one is shown and which one is hidden based on user selection. Thank you for your time


Solution

  • <script>
    
    $(document).ready(function () {
        
        $('.target').on('change', function () {
         if ($(".target").children()[1].selected)
            {
                $(".target1").show();
                $(".target2").hide();
                $(".ddl1").val("");
            }
         else if ($(".target").children()[2].selected)
            {
                $(".target2").show();
                $(".target1").hide();
                $(".ddl2").val("");
            }
    
        });
    });
    

    This is a potential solution for this problem. Other than this I just added some classes in HTML.