Vikash Jha
Vikash Jha

Reputation: 45

document.getElementById("id").value is working but $('#id).val is not working

I have some input fields of text type. I am getting the values from a JSON object and trying to dynamically fill those values using javascript/jquery. When I fill the values using document.getElementById('id').value it works fine. But $('#id').val() gives error.

HTML:

<div class="form-group">
   <label > First Name</label>
   <input type="text" class="form-control" id="txtFirstName"> 
</div>

JavaScript:

var UserID = 25;
function editUser(response)
{
   var obj = response;
   $.each(obj.userDataDTOList, function(index, item){
       if(item.userId == UserID)
       {
           document.getElementById('txtFirstName').value = item.userFirstname;
           //$('#txtFirstName').val() = item.userFirstname;
       }
   });
}

This is the error:

Uncaught ReferenceError: Invalid left-hand side in assignment at Object. (editUser.js:35) at Function.each (jquery.min.js:2)

Upvotes: 0

Views: 2699

Answers (1)

Mamun
Mamun

Reputation: 68933

.val() is a jQuery method that takes the value as parameter to set in the element.

Try

$('#txtFirstName').val(item.userFirstname);

Upvotes: 3

Related Questions