Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set value of input text using jQuery

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?

like image 445
raberana Avatar asked May 16 '12 02:05

raberana


People also ask

How can get value entered textbox using jQuery?

To get the textbox value, you can use the jQuery val() function. For example, $('input:textbox'). val() – Get textbox value.


2 Answers

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.

like image 169
Michael Berkowski Avatar answered Sep 16 '22 15:09

Michael Berkowski


Using jQuery, we can use the following code:

Select by input name:

$('input[name="textboxname"]').val('some value') 

Select by input class:

$('input[type=text].textboxclass').val('some value') 

Select by input id:

$('#textboxid').val('some value') 
like image 34
Aditya P Bhatt Avatar answered Sep 19 '22 15:09

Aditya P Bhatt