Question

Im trying to catch the textbox element by javascript, in order to put text into it. so how to set id to the textbox ??

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

and then to put text into it by JS

                            // 
   document.getElementById("Textbox id").Text= " Some text " ;
Était-ce utile?

La solution

You can set ID of a textbox like this.

@Html.TextBoxFor(item => item.OperationNo, new { id = "MyId" })

OR

@Html.TextBoxFor(item => item.OperationNo, htmlAttributes: new { id = "MyId" })

Output:

<input ... id="MyId" name="OperationNo" type="text" />

Autres conseils

You can use below code for resolve that problem:

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

 @Html.TextBoxFor(m => m.OperationNo,new { @id = "txtPlace",@name="txtPlace" })

It should be the property name, which is OperationNo.

So your JS will be

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

You can use the web inspector in Chrome or JS to view the html on your page to see the element attributes.

This is happens in a scenario of using same input fields with same properties in web form. Like the case of Login and Signup forms in single view/page. Previously it was like this

input one >

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

input two>

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

then i added a unique id # for the username input

the new input one >

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

the new input two >

<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> 
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top