Skip to content
Fix Code Error

How to set value of input text using jQuery

March 13, 2021 by Code Error
Posted By: Anonymous

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.

Answered By: Anonymous

Related Articles

  • What is the worst programming language you ever worked with?
  • Is it possible to apply CSS to half of a character?
  • model validation error message isn't working And Returning…
  • Select Tag Helper in ASP.NET Core MVC
  • Fix top buttons on scroll of list below
  • delete item in array of struct that has char array member in…
  • Trying to keep dropdown menus flush to the edge of header…
  • After a little scroll, the sticky navbar just is not fixed…
  • PL/SQL ORA-01422: exact fetch returns more than requested…
  • PHP A Good way to pass the PDO Object into other Main…

Disclaimer: This content is shared under creative common license cc-by-sa 3.0. It is generated from StackExchange Website Network.

Post navigation

Previous Post:

jQuery – setting the selected value of a select control via its text description

Next Post:

usr/bin/ld: cannot find -l

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

  • Get code errors & solutions at akashmittal.com
© 2022 Fix Code Error