How to Assign Value to Textbox Using JavaScript

In this tutorial, you will learn how to assign value to textbox using javascript. Whenever we need a textbox on our website, we make use of either input element or textarea element.

The input element is best suited for single-line sentences. On the other hand, textarea element is used for multiline sentences.  Both input element and textarea element have a value property. This property can be used to set or get the data from the textbox.

We can take advantage of value property to assign value to the textbox.

In the following example, we have an input element and a button element. Upon click of a button, we will generate some random floating-point value and set it as the value of the textbox. Please have a look over the code example and the steps given below.

HTML & CSS

  • We have 3 elements in the HTML file (div, input, and button). The div element with a class of container is just a wrapper for the rest of the elements.
  • The innerText for the button element is “Assign Value”.
  • We have done some basic styling using CSS and added the link to our style.css stylesheet inside the head element.
  • We have also included our javascript file script.js with a script tag at the bottom.
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <link rel="stylesheet" href="style.css">
  <title>Document</title>
</head>

<body>

  <div class="container">
    <input type="text">
   <button>Assign Value</button>   
  </div>

  <script src="script.js"></script>
</body>

</html>
.container {
    width: 400px;
    margin: auto;
    display: flex;
    flex-direction: column;
}

button, input  {
  padding: 5px 10px;
  margin-bottom: 20px;
}

Javascript

  • We have selected the input element and the button element using the document.querySelector() method and stored them in input and btn variables respectively.
  • We have attached the click event listener to the button element.
  • In the event handler function, we are generating random floating-point value by using the Math.random() method and storing it in the randomValue variable.
  • We are assigning randomValue to the input element by using value property.
let input = document.querySelector("input");
let btn = document.querySelector("button");

btn.addEventListener("click", () => {
  let randomValue = Math.random();
  input.value = randomValue;
});