我试图通过javascript捕获textbox元素,以便将文本放入其中。那么如何设置id到文本框??
<tr>
// Id to this textbox
<td>@Html.TextBoxFor(item => item.OperationNo)</td>
</tr>
,然后通过JS
将文本放入其中 //
document.getElementById("Textbox id").Text= " Some text " ;
可以这样设置文本框的ID。
@Html.TextBoxFor(item => item.OperationNo, new { id = "MyId" })
或
@Html.TextBoxFor(item => item.OperationNo, htmlAttributes: new { id = "MyId" })
输出:<input ... id="MyId" name="OperationNo" type="text" />
你可以使用下面的代码来解决这个问题:
function steVal() {
document.getElementById('txtPlace').value = "Set The Text";
}
@Html.TextBoxFor(m => m.OperationNo,new { @id = "txtPlace",@name="txtPlace" })
应该是属性名,即OperationNo
。
所以你的JS将是
document.getElementById("OperationNo").html = " Some text " ;
你可以使用Chrome或JS中的web检查器来查看页面上的html,以查看元素属性
这种情况发生在web表单中使用具有相同属性的相同输入字段的场景中。就像登录和注册表单在单一视图/页面的情况。以前是这样的
输入1>
<div class="field-wrap">
@Html.TextBoxFor(model => model.Username, new { @class = "form-control",placeholder = "Username", @required = "required", autofocus = "" })
@Html.ValidationMessageFor(model => model.Username, "", new { @class = "text-danger" })
</div>
输入两个> <div class="field-wrap">
@Html.TextBoxFor(model => model.Username, new { @class = "form-control", placeholder = "Username", @required = "required", autofocus = "" })
@Html.ValidationMessageFor(model => model.Username, "", new { @class = "text-danger" })
</div>
然后我添加了一个唯一的id #为用户名输入
新输入1>
<div class="field-wrap">
@Html.TextBoxFor(model => model.Username, new { @class = "form-control", id = "loginUsername", placeholder = "Username", @required = "required", autofocus = "" })
@Html.ValidationMessageFor(model => model.Username, "", new { @class = "text-danger" })
</div>
新输入二>
<div class="field-wrap">
@Html.TextBoxFor(model => model.Username, new { @class = "form-control", id = "SignupUsername" , placeholder = "Username", @required = "required", autofocus = "" })
@Html.ValidationMessageFor(model => model.Username, "", new { @class = "text-danger" })
</div>