In MVC4 I have an EditorFor field which represents a boolean and is rendered as a checkbox, I want to make other EditorFor fields change to uneditable if the checkbox is ticked. This would be simple in plain html but with razor syntax I’m not sure how to do this.
<div class="editor-field">
@Html.EditorFor(model => model.Draw)
@Html.ValidationMessageFor(model => model.Draw)
</div>
<script type="text/javascript">
function validate() {
if (document.getElementById('@Html.EditorFor(model => model.Draw)').checked) {
alert("checked")
} else {
alert("You didn't check it! Let me check it for you.")
}
}
Was trying to test it with that script but as I dont know the ID of the editorfor i’m unsure what to do.
If you use CheckBoxFor instead of EditorFor (which is a generic helper), you can easily add HTML attributes through a method overload. Adding an ID allows you to access it from your JavaScript.
(Note: This example uses jQuery)