Reputation: 139
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.
Upvotes: 2
Views: 10120
Reputation: 298
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.
<div class="editor-field">
@Html.CheckBoxFor(model => model.Draw, new { ID = "cbxDraw" })
@Html.ValidationMessageFor(model => model.Draw)
</div>
<script type="text/javascript">
$(document).ready(function() {
$('#cbxDraw').on('change', function() {
var $cbx = $(this),
isChecked = $cbx.is(':checked');
$cbx.closest('.editor-field')
.siblings()
.find(':input')
.prop('disabled', isChecked);
});
});
</script>
(Note: This example uses jQuery)
Upvotes: 5
Reputation: 24125
ASP.NET MVC 4 has new NameExtensions
class which provides IdFor
and NameFor
methods. You can use it like this:
document.getElementById('@Html.IdFor(model => model.Draw)')
Upvotes: 5