Reputation: 1496
I have a DropDownList and a TextArea in a Razor View. I want the TextArea to be visible only if specific value in the drop down has been selected. what solution is there to do that? Here is what I have tried so far but it is not quite right because it assumes the value of Security type is set.
<tr>
<td style="width: 200px; height: 30px">
@Html.LabelFor(model => model.SecurityTypeId)
</td>
<td style="width: 400px; height: 30px">
@Html.DropDownListFor(model => model.SecurityTypeId, Model.SecurityTypes, dropdownHtmlAttrs)
</td>
<td> </td>
</tr>
<tr>
@if (Model.SecurityTypeId == (int)(SecurityType.Other))
{
<td style="width: 200px; height: 30px">
@Html.LabelFor(model => model.Details)
</td>
<td style="width: 400px; height: 30px">
@Html.TextAreaFor(model => model.Details, new { Style = "width:240px" })
</td>
<td> </td>
}
</tr>
Upvotes: 0
Views: 1778
Reputation: 24957
Use jQuery when handling visibility of view element(s) on client-side event, with show
or hide
method. Here is an example:
<script type="text/javascript">
$(document).ready(function () {
$('#SecurityTypeId').change(function () {
var value = $(this).val(); // get selected value
if (value == "set") { // this condition may adjusted to certain preset value
$('#Details').show(); // show text area
}
else {
$('#Details').hide(); // hide text area
}
});
});
</script>
If you prefer using vanilla JS:
<script type="text/javascript">
var ddlvalue = document.getElementById("SecurityTypeId").value;
if (ddlvalue == "set") {
document.getElementById("Details")).style.visibility = "visible";
}
else {
document.getElementById("Details")).style.visibility = "hidden";
}
</script>
Those scripts above assume id attribute of DropDownListFor
and TextAreaFor
are exactly same as the model binding name, depending on your needs.
AFAIK, if statement inside Razor works when a view performing callback or postback, thus only changes visibility after an ajax function or a form submit.
Any suggestions and improvements welcome.
References:
how to hide and show text box according to select value using jquery
Show/hide control based on dropdown selection mvc 4 razor c#
Upvotes: 1