How to store User Input in a Variable with JavaScript

As I learning to code, I come across many challenges that require me to look stuff up. I am still at the beginning of my journey, but I try to solve at least one of the Reddit Daily Programmer challenges every day. Today’s task requires me to store User Input in a Variable with JavaScript.

Therefore, we have to create a simple HTML file with a form and a button to submit the text input. Also, we need a JavaScript file to store user input in a variable.

The HTML File

The HTML part is as simple as it gets.

<!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">
  <title>Document</title>
</head>

<body>

    <h1>Storing User Input in a Variable</h1>
    <p>Enter some text</p>
    <input id="userInput" type="text" placeholder="Text">
    <button onclick="returnText()">Submit</button>



  <!-- Optional JavaScript -->
  <script src="order.js"></script>

</body>

</html>

Let’s break this code down a bit.

The <h1> and the <p> parts should be pretty clear.

Next, we have created an input form with the type ‘text’ and we assigned it the ID ‘userInput’.

Below that, we have created a button with an onclick function. This function is called when the user clicks on the button.

The JavaScript File

The JavaScript part is pretty simple too. To be able to store user input in a variable, we need to create a function that is called once the user presses the button. Also, we need to create a variable that pulls that input from the input form.

function returnText(){
    let input = document.getElementById("userInput").value;
    alert(input)
}

Let’s break it down as well.

We declare the function called ‘returnText()’, as you remember, this function is called once the user clicks the button.

Inside this function, we declare a variable called input and we set it equal to the ID ‘userInput’. If you recall, we assigned the ID ‘userInput’ to our input form.

In the end, we simply create an alert that returns the input back to the user, confirming that it was stored successfully in our ‘input’ variable.

As you can see, the entered value was stored in the variable and can be used for further processing.

Tell us what you think!

This site uses Akismet to reduce spam. Learn how your comment data is processed.