我正在为此苦恼, 在 MVC 上工作,在更改 Html.TextBoxFor 值时,我想更改另一个 Html.TextBoxFor 的只读属性。 我尝试了几种方法——用IE还是不行。 这里有一些代码:
@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>
以及我想要更改的表中的行:
<td id="NoDiffNum">@Html.TextBoxFor(model => model.Topics[i].NumberOfNoDifficulltySet)</td>
只读属性没有改变 - 非常欢迎任何帮助!
最佳答案
document.getElementById("NoDiffNum")
指<td>
元素而不是文本框。您正在 td 上设置只读。
您需要定位文本框,而不是 td
,因此将 id 移至文本框。
<td>@Html.TextBoxFor(model => model.Topics[i].NumberOfNoDifficulltySet, new { id="NoDiffNum" })</td>
没有 jQuery
function ReadOnlyHandle() {
var startHSelect = document.getElementById("NoDiffNum");
startHSelect.setAttribute("readonly", "readonly");
}
在你的函数中使用 jQuery
function ReadOnlyHandle() {
$("#NoDiffNum").prop("readonly", true);
}
如果我们使用 jQuery,我们可以删除内联 onchange
@Html.TextBoxFor(x => x.NumberOfQuestion, new { id = "ExamOptions" })
我们设置了一个处理程序
$(document).ready(function() {
$("#ExamOptions").on("change", function(event) {
ReadOnlyHandle();
});
});
编辑
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>
从您的评论来看,现在不太清楚您想要设置只读的内容。但无论如何,您都可以在更改处理程序中调整目标 id。
var targetId = "NumberOfQuestion";
$("#" + targetId).prop("readonly", true);
关于javascript - 打开和关闭更新 Html.TextBoxFor "readonly"属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29971889/