在复选框

时间:2015-05-04 14:11:52

标签: javascript asp.net-mvc

我正在使用mvc,我需要更改元素Html.CheckBoxFor的“readonly”和“disabled”属性。我正在使用JavaScript:

function ReadOnlyHandle() {
            var Collection = document.getElementsByClassName("SubjectCB");
            debugger;
            for (var i = 0; i < Collection.length; i++)
            {
                Collection.item(i)..("disabled", "disabled");
                Collection.removeAttribute("readonly", "readonly");
            }

        debugger;
    }

我正在尝试获取复选框的集合(因为我很少),然后迭代它们以更改其属性。

@for (int i = 0; i < Model.Topics.Count(); i++)
                {
                    <tr id="row-@i">
                        <td>@Html.LabelFor(t => t.Topics[i].Box.Selected, Model.Topics[i].Box.Text)</td>
                        <td class="SubjectCB">@Html.CheckBoxFor(t => t.Topics[i].Box.Selected, new { @checked = "checked", @readonly = "readonly", @disabled = "disabled" })</td>
                        <td class="IsReadOnly">@Html.TextBoxFor(model => model.Topics[i].NumberOfNoDifficulltySet, new { @readonly = "readonly" })</td>
                        <td class="IsReadOnly">@Html.TextBoxFor(model => model.Topics[i].NumberOfEasy, new { @readonly = "readonly" })</td>
                        <td class="IsReadOnly">@Html.TextBoxFor(model => model.Topics[i].NumberOfMedium, new { @readonly = "readonly" })</td>
                        <td class="IsReadOnly">@Html.TextBoxFor(model => model.Topics[i].NumberOfHard, new { @readonly = "read" })</td>
                    </tr>
                }

然而,在集合中,Javascript中定义的变量没有“removeAttribute”函数 - 为什么?或者我可以用另一种方式更改属性吗?

1 个答案:

答案 0 :(得分:0)

首先,在实际复选框上设置类而不是td(或为其创建另一个类):

<td>
      @Html.CheckBoxFor(t => t.Topics[i].Box.Selected, 
           new { 
                 @checked = "checked", 
                 @readonly = "readonly", 
                 @disabled = "disabled", 
                 @class = "SubjectCB" 
               }
      )
</td>

接着..
您正在尝试从整个集合中删除属性。使用disabledreadOnly

,这应该会更好
Collection[i].disabled = false; //or true
Collection[i].readOnly = false; //or true

或者:

Collection[i].removeAttribute("readonly");

应该注意,虽然readOnly 在复选框上非常有用(如果有的话)。

相反,如果你想使用类似readonly的东西,可以发布here的工作:

<input type="checkbox" onclick="return false;" />

编辑:显然我忘了从代码中删除.item。现已更正。