Reputation:
I've got a textbox that I only want to show if the value of Model.SelectedSubProcessID
is -2
.
<script>
$(function () {
$('#subProcessAdditionalDiv').hide();
});
</script>
<div id="modifyForm" class="incidentBox" style="justify-content: flex-start !important; width: auto !important; padding-left: 20px; text-align: left; align-items: flex-start !important;">
...
if (Model.SelectedSubProcessID == -2)
{
<script type="text/javascript">
$('#subProcessAdditionalDiv').show();
</script>
}
...
</div>
<br />
<div id="subProcessAdditionalDiv" style="display:flex; margin-bottom:10px">
@Html.LabelFor(m => m.SelectedSubProcessName, new { style = "margin-top: 2px" })<span> </span>
@Html.TextBoxFor(m => m.SelectedSubProcessName, new { style = "width:500px; margin-left: 120px" })<span> </span>
@Html.ValidationMessageFor(m => m.SelectedSubProcessName)
</div>
Even when the if statement is true the line $('#subProcessAdditionalDiv').show();
does not execute and the textbox remains hidden, why is this?
Upvotes: 0
Views: 71
Reputation: 219096
You forgot to wrap the statement in the document's ready handler like you previously did above:
$(function () {
$('#subProcessAdditionalDiv').show();
});
By not using the document's ready handler the code is trying to execute immediately as the browser is parsing the document, and the target element doesn't exist yet because it's later in the document. So the code is running in your example, the jQuery selector simply doesn't find any matching elements to show.
Note that putting two mutually exclusive statements into the document's ready handler might work, but just in case there's no guarantee about the order in which they're executed wouldn't it make more sense to wrap the condition around just one of the statements? Remove the top one (the call to .hide()
) entirely and style the element to be hidden by default. Then your conditional call to .show()
will show the element when it's needed. (Or style it to be shown by default and negate the condition to hide it.)
Additionally, you probably don't need to use JavaScript at all for this. Just wrap the element itself in the condition and it won't be sent to the client at all when the condition isn't met:
@if (Model.SelectedSubProcessID == -2)
<div id="subProcessAdditionalDiv" style="display:flex; margin-bottom:10px">
...
</div>
}
Upvotes: 5