39

我试图通过 javascript 捕获文本框元素,以便将文本放入其中。那么如何将 id 设置为文本框?

        <tr>
                    // Id to this textbox
            <td>@Html.TextBoxFor(item => item.OperationNo)</td>
        </tr>

然后通过JS将文本放入其中

                            // 
   document.getElementById("Textbox id").Text= " Some text " ;
4

4 回答 4

79

您可以像这样设置文本框的 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" />
于 2013-06-06T18:24:21.463 回答
8

您可以使用以下代码来解决该问题:

function steVal() {
        document.getElementById('txtPlace').value = "Set The Text";
    }

 @Html.TextBoxFor(m => m.OperationNo,new { @id = "txtPlace",@name="txtPlace" })
于 2013-09-19T10:12:40.410 回答
5

它应该是属性名称,即OperationNo.

所以你的 JS 将是

document.getElementById("OperationNo").html = " Some text " ;

您可以使用 Chrome 或 JS 中的网络检查器查看页面上的 html 以查看元素属性。

于 2013-06-06T18:19:23.773 回答
0

这是在 Web 表单中使用具有相同属性的相同输入字段的情况下发生的。就像单个视图/页面中的登录和注册表单的情况一样。以前是这样的

输入一个 >

<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 #

新输入一个 >

<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> 
于 2018-10-04T07:46:30.883 回答