How to Get and Set the Value of an Input Text Field in JavaScript

08/02/2021

Contents

In this article, you will learn how to get and set the value of an input text field in JavaScript.

Getting and Setting the value of an input text field in JavaScript

In JavaScript, you can get and set the value of an input text field using the value property of the HTMLInputElement interface.

Getting the value of an input text field

const inputField = document.getElementById('my-input-field');
const inputValue = inputField.value;
console.log(inputValue); // Output: "Hello World"

In this example, the getElementById() method is used to get the input field element with the ID of my-input-field. The value property is then used to get the current value of the input field, which is assigned to the inputValue variable.

Setting the value of an input text field

const inputField = document.getElementById('my-input-field');
inputField.value = 'New Value';

In this example, the getElementById() method is used to get the input field element with the ID of my-input-field. The value property is then used to set the new value of the input field, which is the string ‘New Value’.

It’s important to note that the value property returns a string value, even if the input field is a number or a boolean. If you want to get the number value of an input field, you can use the parseFloat() or parseInt() methods to convert the string value to a number value.

Example
const inputField = document.getElementById('my-input-field');
const inputValue = parseFloat(inputField.value);
console.log(inputValue); // Output: 123.45

In this example, the parseFloat() method is used to convert the string value of the input field to a floating-point number value, which is assigned to the inputValue variable.