Change an TextBoxFor readonly property on whether a checkbox is checked or not

585 Views Asked by At

I'm trying to change an TextBoxFor readonly property on whether a checkbox is checked or not. I have read other posts but the answers don't seem to work for me.. I any one please would point out what i miss in the code below.

<div class="editor-label">
                @Html.LabelFor(m => m.AddFitbit)
            </div>
            <div class="editor-field" id="checkBox">
                @Html.CheckBoxFor(m => m.AddFitbit)
            </div>
            <div class="editor-label">
                @Html.LabelFor(m => m.Mail)
            </div>
            <div class="editor-field" id="userMail">
                @Html.TextBoxFor(m => m.Mail)
            </div>
            <br />
            <input class="submit" type="submit" value="@LangResources.Create" />
            <button onclick="history.back(); return false;">@LangResources.BtnCancel</button>
        </div>
    </article>
}

@Html.ValidationSummary(true, LangResources.ScreenAddGeneralError)

<script type="text/javascript">
    $(function() {
        $('#checkBox').change(function () {
            if ($(this).is(':checked')) {
                $('#userMail').attr('readonly');
            } else {
                $('#userMail').removeAttr('readonly');
            }
        });
    });
</script>
1

There are 1 best solutions below

1
On BEST ANSWER

You target the div which contains your checkbox, which indeed doesn't trigger any change events. Target the checkbox inside the div like this.

$(function() {
    $('#checkBox input[type="checkbox"]').change(function () {
        $('#userMail input[type="text"]').prop('readonly', $(this).is(':checked'));
    });
});

Also, I corrected and simplified your code by using prop instead of attr. Attributes should mean an initial value of a given property, so it's a better practice to change the corresponding element property instead.

For details about using prop, see the documentation (based on @Liam's comment).