Hide html input based on dropdownlist's value in ASP.NET MVC

In this article we will explain how to show or hide form fields based on dropdownlist's value in asp.net mvc 5.


<div class="col-12 col-md-6">
    <div class="form-group">
        @Html.LabelFor(m => m.ProcessID)
        @Html.DropDownListFor(m => m.ProcessID, new SelectList(Model.processes, "ID", "Name"), new { @class = "form-control", onchange = "GetSelectedTextValue(this)" })
        @Html.ValidationMessageFor(m => m.ProcessID, null, new { @class = "text-danger" })
    </div>
</div>

When an item is selected in the dropdownlist, the javascript onchange event handler is executed.


GetSelectedTextValue(this) will give you the selected value of the dropdownlist element.


The following code snippet shows or hides the "Price" form field based on dropdownlist's value. If user selects "26", it shows the "Price" form field.


function GetSelectedTextValue(processes) {
    //var selectedText = processes.options[processes.selectedIndex].innerHTML;
    var selectedValue = processes.value;
    //alert("Selected Text: " + selectedText + " Value: " + selectedValue);
    //26 - Application
    if (selectedValue == "26") {
        $('#mydiv').show();
    }
    else {
        $('#mydiv').hide();
    }
}

We have an input field inside of a div with id of "mydiv" as shown below.


<div class="col-12 col-md-6">
    <div class="form-group" id="mydiv">
        @Html.LabelFor(m => m.Price)
        @Html.TextBoxFor(m => m.Price, new { @class = "form-control", type = "text", autocomplete = "off" })
        @Html.ValidationMessageFor(m => m.Price, null, new { @class = "text-danger" })
    </div>
</div>

With jQuery, we need to use the ready event when the DOM has been loaded.


<script>
    $(document).ready(function () {
        var selectedValue = $('#ProcessID').val();
        
        //26 - Application
        if (selectedValue == "26") {
            $('#mydiv').show();
        }
        else {
            $('#mydiv').hide();
        }
    });
</script>

Output :


hide-input-based-on-dropdownlist-1.JPG

hide-input-based-on-dropdownlist-2.JPG

hide-input-based-on-dropdownlist-3.JPG

Tag : asp.net mvc 5 dropdownlist onchange, show or hide form fields based on dropdownlist's value in asp.net mvc 5