As I am still 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.
For this task, we will create a simple index.html
file and a script.js
file. After writing our code, we will utilize an alert() to check if the user input was stored in the variable.
ℹ️ This article has a corresponding Replit repository that you can copy and play around with. Create a free Replit account and click on the Fork Repl button below. This is the best way to practice programming!
Table of Contents
The HTML File
The HTML part is as simple as it gets.
index.html:
<!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="script.js"></script>
</body>
</html>
Code language: HTML, XML (xml)
Let’s break this code down:
- The
<h1>
and the<p>
parts should be pretty clear. - Next, we created a
input
form withtype="text"
and we assigned it the IDuserInput
. - Below that, we have created a button with a
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.
script.js:
function returnText(){
let input = document.getElementById("userInput").value;
alert(input)
}
Code language: JavaScript (javascript)
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 IDuserInput
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.
Using the Variable Outside of the Function
As some readers have correctly pointed out, of course, the variable that we declare and set inside of the function can only be used within the function. If you want to use the variable and its value outside of the function scope, you have to utilize localStorage
.
To that, modify the script.js
file as follows:
let input = localStorage.getItem('input')
function returnText() {
input = document.getElementById("userInput").value
localStorage.setItem('input', input)
alert(input)
}
console.log(input)
Code language: JavaScript (javascript)
With this, you now have access to the input variable outside of the function.
Summary
You can easily store user input in a variable with JavaScript by using the above method. To summarize:
- We need to create an
input
field with an ID and anonClick
listener. - We need to create a JavaScript file that stores our variable.
- If we want to use the
input
variable outside of the function, we have to use thelocalStorage
object.
🔥 Learn JavaScript Programming – Beginner Friendly!
🔨 JavaScript Basics
👉 JavaScript alert()
👉 Difference between Let and Const
🔸 JavaScript Arrays
👉 JavaScript Array Filter
👉 JavaScript Array Find
👉 JavaScript forEach (Arrays)
👉 JavaScript Slice (Arrays)
👉 JavaScript Spread Operator
🔸 JavaScript Strings
👉 JavaScript Slice(Strings)
👉 JavaScript Includes
🌐 Web Development with JavaScript
👉 Store User Input in a variable with JS
⚙️ JavaScript Specifics
👉 Sorting Numbers in JS
👉 JavaScript Fetch API
👉 toLocaleDateString in JavaScript
Really thank you. it worked out for me. I was searching for this for about 3 hours!
Most welcome 🙂
I’m pretty sure the input was NOT stored in the variable for future use.
You put the alert within the returnText() function, but didn’t show us how to save it into a variable for use outside of the function. “input” is a local variable that works within the function, not a global variable that works outside of it.
Correct me if I’m wrong. I, like Patrick am trying to figure out how to store it in a variable that can be used outside of that specific function.
Hi Elijah,
you are correct. It is temporarily stored inside of the variable in that function. To use it outside you have to utilize localStorage.
Here is an example:
let input = localStorage.getItem(‘input’)
function returnText() {
input = document.getElementById(“userInput”).value
localStorage.setItem(‘input’, input)
alert(input)
}
console.log(input)
Hi,
I have tried using this and it works but the results appear on console.log when you refresh the page? Not when you click submit.
Is this normal?
Thank you
I’m having an issue in one of my projects where I need the value of an tag to be global (or at least used in two different functions), and I can NOT figure it out. Help please!