Friday, September 6, 2013

Make field readonly with Javascript

In this post I will show an example of making a textbox that is bound to a model, read-only/editable when a user checks/unchecks a checkbox.

Our controls will start in the following state: the checkbox (chkIsReadOnly) is unchecked and the textbox is editable.

When the user clicks on the checkbox the following javascript function will be launched:

function changeState() {
            var checkValue = document.getElementById("chkIsReadOnly").checked;
            var userName= document.getElementById("userName");

            if (!checkValue) {
               //the field becomes readonly since the checkbox is checked
                userName.readOnly = false;
                userName.removeAttribute('readonly');
                userName.removeAttribute('disabled');
            }
            else {

                userName.readOnly = true;
                userName.setAttribute('readonly', true);
                userName.setAttribute('disabled', true);
                userName.value = '';
            }

        };

The checkbox is defined like this:
<input
                            type="checkbox"
                            name="chkIsReadOnly"
                            id="chkIsReadOnly"
                            onclick="changeState()"
  />

In order for the javascript function to work we must use the HTML helper TextBoxFor instead of EditorFor

@Html.TextBoxFor(model => model.userName, new { disabled = "disabled", @readonly = "readonly" })

No comments:

Post a Comment