您好我正在尝试在mvc 5中的javascript + jquery中为textarea和复选框设置我的值,但它不起作用。
我的javscript代码为
document.getElementById("UpdatetxtDescription").value = "abc";
document.getElementById("UpdateActive").checked = true;
我的观看页面代码为
@Html.TextAreaFor(model => model.Description, new { htmlAttributes = new { @class = "form-control", id = "UpdatetxtDescription" } })
@Html.CheckBoxFor(model => model.Active, new { htmlAttributes = new { @class = "form-control", id = "UpdateActive" } })
在控制台中我能看到
<input data-val="true" data-val-required="The Active field is required." htmlattributes="{ class = form-control, id = UpdateActive }" id="Active" name="Active" type="checkbox" value="true">
<textarea cols="20" htmlattributes="{ class = form-control, id = UpdatetxtDescription }" id="Description" name="Description" rows="2"></textarea>
我可以设置id =&#34;描述&#34;和id =&#34;活跃&#34;坚果,因为我有2个复选框和2个文本区域我无法使用该ID,因为两个控件都具有与textarea的decription相同的id和用于复选框的Active
第二个textarea和复选框如下所示我的ID设置为不同
@Html.TextAreaFor(model => model.Description, new { htmlAttributes = new { @class = "form-control", id = "txtDescription", rows = "3" } })
@Html.CheckBoxFor(model => model.Active, new { htmlAttributes = new { @class = "form-control", id = "txtDescription" } })
但在控制台我可以看到Id为
<textarea cols="20" htmlattributes="{ class = form-control, id = txtDescription, rows = 3 }" id="Description" name="Description" rows="2"></textarea>
<input data-val="true" data-val-required="The Active field is required." htmlattributes="{ class = form-control, id = txtDescription }" id="Active" name="Active" type="checkbox" value="true">
答案 0 :(得分:1)
您正在以错误的方式设置HTML帮助程序的htmlAttributes
参数。如果您看到生成的HTML,则可以看到未设置id
和class
。但是attribute
本身的htmlAttributes
就像这样添加:
<textarea cols="20" htmlattributes="{ class = form-control, id = UpdatetxtDescription }"></textarea>
所以你应该把它改成:
@Html.TextAreaFor(model => model.Description, new { @class = "form-control", id = "UpdatetxtDescription" })
@Html.CheckBoxFor(model => model.Active, new { @class = "form-control", id = "UpdateActive" })
和
@Html.TextAreaFor(model => model.Description, new { @class = "form-control", id = "txtDescription", rows = "3" })
@Html.CheckBoxFor(model => model.Active, new { @class = "form-control", id = "txtDescription" })
(PS:如果您要提交此表单,则只有一个textarea和复选框将绑定到模型,因为您创建了多个具有相同name
属性的输入。
答案 1 :(得分:0)
id
在同一文档中对于有效结构应该是唯一的,如果您无法更改它,那么您可以使用jQuery选择器来处理这种重复:
$('[id="Description"]:eq(0)') //Select the first element with id "Description"
$('[id="Description"]:eq(1)') //Select the second element with id "Description"
第二个元素input
同样如此:
$('[id="Active"]:eq(0)') //Select the first element with id "Active"
$('[id="Active"]:eq(1)') //Select the second element with id "Active"
希望这有帮助。