Lior Smila
Lior Smila

Reputation: 23

update Html.TextBoxFor "readonly" attribute on and off

I'm srugelling with this, Working on MVC, upon change on Html.TextBoxFor value I want to change a readonly attribute of another Html.TextBoxFor. I tried several ways-using IE it does not work. here some code:

@Html.TextBoxFor(x => x.NumberOfQuestion, new { id = "ExamOptions", onchange = "javascript:ReadOnlyHandle();" })

<script>
    function ReadOnlyHandle() {
        //document.getElementById("NoDiffNum").readOnly = true;
        var startHSelect = document.getElementById("NoDiffNum");
        debugger;
        startHSelect.setAttribute("readonly", "true");
    }
    debugger;
</script>

and the row in a table I would like to change:

<td id="NoDiffNum">@Html.TextBoxFor(model => model.Topics[i].NumberOfNoDifficulltySet)</td>

the readonly attribute did not changed - any help is most welcome!

Upvotes: 1

Views: 4534

Answers (1)

Jasen
Jasen

Reputation: 14250

document.getElementById("NoDiffNum") refers to the <td> element not the text box. You are setting readonly on the td.

You need to target the text box, not the td, so move the id to the text box.

<td>@Html.TextBoxFor(model => model.Topics[i].NumberOfNoDifficulltySet, new { id="NoDiffNum" })</td>

Without jQuery

function ReadOnlyHandle() {
    var startHSelect = document.getElementById("NoDiffNum");
    startHSelect.setAttribute("readonly", "readonly");
}

And with jQuery in your function

function ReadOnlyHandle() {
    $("#NoDiffNum").prop("readonly", true);
}

If we use jQuery we can drop the inline onchange

@Html.TextBoxFor(x => x.NumberOfQuestion, new { id = "ExamOptions" })

And we setup a handler

$(document).ready(function() {
    $("#ExamOptions").on("change", function(event) {
        ReadOnlyHandle();
    });
});

Edit

Based on a value in TextBoxFor element value I want another TextBoxFor element to change its readonly attribute on and off. <div class="editor-field"> @Html.TextBoxFor(x => x.NumberOfQuestion, new { id = "ExamOptions", onchange = "javascript:ReadOnlyHandle();" }) @*@Html.EditorFor(model => model.NumberOfQuestion)*@ @Html.ValidationMessageFor(model => model.NumberOfQuestion) </div>

From your comments it's now less clear what you want to set readonly. But in any case you adjust the target id in the change handler.

 var targetId = "NumberOfQuestion";
 $("#" + targetId).prop("readonly", true);

Upvotes: 1

Related Questions