To get the value from an input field, we can use the value property. We can also use the value property to set the value of an input field.

var userInput = document.getElementById("input1").value;

Let’s say we have the following HTML:

To get the value that the user has entered for “Full Name”, we would use the value property.

document.getElementById("fname").value;

This can also be done using jQuery with the val() method.

Get and Set an Input Field using JavaScript and the value Property

In this example, we will have a form that will display the information of a user. We will then let the user update one of the fields by using an input field and submit button below it.

Here is the HTML setup:

Update

In the JavaScript code below, we will get the user input using the value property, and then set the input value “Username” in the form above using the value property again along with the getElementById method.

Here is the JavaScript code for getting and setting an input field:

function updateUsername(){
  var userInput = document.getElementById("new-username").value;
  document.getElementById("username").value = userInput;
};

The final code and output for this example of getting and setting an input field using JavaScript and the value property is below:

Code Output:






Update

Full Code:

Update
<script> function updateUsername(){ var userInput = document.getElementById("new-username").value; document.getElementById("username").value = userInput; }; </script>

Hopefully this article has been useful to help you understand how to use the value property to get the value from an input field.

Categorized in:

JavaScript,

Last Update: March 20, 2024