How to take user input in HTML form and store in JavaScript variable

In this tutorial, we will learn how to take user input in HTML form and store it in a JavaScript variable.

And then, we can do whatever we want to do with it like mathematical operations if our input is a number or display it.

We will be seeing how to see if user input is available and then just show a greeting message to the user from the website.

<input id="userinput" > <br><br>

<button onclick="greetings()"> Click ME!! </button> <br>

In the above HTML program, I have created an HTML file with an input form and set it equal to Id ‘userinput‘.

After that, we created a function “greetings” that is called when the user clicks on the button. This function onclick¬†is created along with a button.

function greetings() {
var adj=document.getElementById("userinput").value;

document.write("Hello!!, "+adj);
}

Here, we have used document.getElementById . Using this method in JavaScript, we target an element with the help of Id.

We also have created a variable called adj that will take that input from the input form and save it. Once the user clicks the button, this function is called.

Finally whatever user types, will be displayed.

This is how we can save user input as a variable and then can perform a lot of things with the help of the variables.

Leave a Reply

Your email address will not be published. Required fields are marked *