javascriptjqueryhtmlasp.net-mvc-3

How to use jQuery to set value of an input element generated by ASP.NET MVC?


I have an input text which is this:

<div class="editor-label">
    @Html.LabelFor(model => model.EmployeeId, "Employee Number")
</div>

<div class="editor-field textBoxEmployeeNumber">
    @Html.EditorFor(model => model.EmployeeId) 
    @Html.ValidationMessageFor(model => model.EmployeeId)
</div>

Which produce following html

<div class="editor-label">
  <label for="EmployeeId">Employee Number</label>
</div>

<div class="editor-field textBoxEmployeeNumber">
  <input class="text-box single-line" data-val="true" data-val-number="The field EmployeeId must be a number." data-val-required="The EmployeeId field is required." id="EmployeeId" name="EmployeeId" type="text" value="" />

  <span class="field-validation-valid" data-valmsg-for="EmployeeId" data-valmsg-replace="true"></span>
</div>

I want to set the value of this input text using jquery so i did this:

<script type="text/javascript" language="javascript">
    $(function() {
        $('.textBoxEmployeeNumber').val("fgg");
    });
</script> 

however, it is not working... what is the error in my syntax?


Solution

  • Your selector is retrieving the text box's surrounding <div class='textBoxEmployeeNumber'> instead of the input inside it.

    // Access the input inside the div with this selector:
    $(function () {
      $('.textBoxEmployeeNumber input').val("fgg");
    });
    

    Update after seeing output HTML

    If the ASP.NET code reliably outputs the HTML <input> with an id attribute id='EmployeeId', you can more simply just use:

    $(function () {
      $('#EmployeeId').val("fgg");
    });
    

    Failing this, you will need to verify in your browser's error console that you don't have other script errors causing this to fail. The first example above works correctly in this demonstration.