2

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.

2 Answers 2

5

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)

Sign up to request clarification or add additional context in comments.

2 Comments

This is perfect, but it also makes the save button uneditable is there a way for this to not happen? Cheers.
It's ok, I just gave the other ediors a class and disabled those. Cheers.
5

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)')

1 Comment

I didn't know that MVC offered this, thanks I will definitely use these in the future.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.