Share via


make @Html.EditorFor readonly depending on dropdown list

Question

Wednesday, July 24, 2019 8:08 PM

How can I make @Html.EditorFor read only by the value of a dropdown list - on change. I have a drop down that on change is either True or False. So once that value changes how can I make the editor read only.

<select class="form-control" id="Type" name="Type">
    <option value="">- Please Select Type -</option>
    <option value="True">Document</option>
    <option value="False">Link</option>
</select>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">


        $("#Type").change(function () {
            var deptId = $(this).val();
            alert(deptId);
});

</script>

        <div class="form-group">
            @Html.LabelFor(model => model.Description, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Description, new { htmlAttributes = new { @class = "form-control"} })
                @Html.ValidationMessageFor(model => model.Description, "", new { @class = "text-danger" })
            </div>
        </div>

All replies (3)

Wednesday, July 24, 2019 8:33 PM âś…Answered

I think you are looking for code similar to the following.  

<div>
    <select class="form-control" id="Type" name="Type">
        <option value="">- Please Select Type -</option>
        <option value="True">Document</option>
        <option value="False">Link</option>
    </select>

    <input type="text" id="Description" name="Description" />
</div>


@section scripts {
    <script>
        $("#Type").change(function () {
            var readonly = $(this).val() == "False";
            $('#Description').attr('readonly', readonly);
        });
    </script>
}

Wednesday, July 24, 2019 8:41 PM

is there anyway to hide it instead of read only?


Wednesday, July 24, 2019 9:19 PM

is there anyway to hide it instead of read only?

It's the same idea.

$("#Type").change(function () {
    if ($(this).val() == "False") {
        $('#Description').hide();
    } else {
        $('#Description').show();
    }
});