Kodeclik Logo

Our Programs

Courses

Gifting

Learn More

Schedule

Kodeclik Blog

How to get user input in Javascript

We will write Javascript programs to receive and react to user input dynamically. For this purpose, we will write a Javascript program and embed it inside a HTML page like so:

<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>How to get user input in Javascript</title>
</head>

<body>
  <script>
  </script>
</body>

</html>

In the above HTML page you see the basic elements of the page like the head element containing the title (“How to get user input in Javascript”) and a body with an empty script tag. Any HTML markup goes inside the body tags and any Javascript code goes inside the script tags.

The prompt() method

How to get user input in Javascript

The prompt() method displays a message and solicits user input. When user input is received it returns it that can be stored in a variable and processed further in your Javascript program. Consider the following program:

<script>
  var myname = prompt("What is your name?")
  document.write("Welcome " + myname + "!<BR>")
</script>

This program prompts “What is your name?” The result of the prompting is stored in the variable “myname” which is then used to write to the page. If we entered “Kodeclik” we will obtain:

Welcome Kodeclik!

The prompt() method with two arguments

In the above program if you just clicked on “OK” without entering any input, you will get:

Welcome !

Similarly, if you pressed on “Cancel” at the prompt, you will get:

Welcome null!

We can update the statement with the prompt() method to provide a default value:

<script>
  var myname = prompt("What is your name?", "Harry Potter")
  document.write("Welcome " + myname + "!<BR>")
</script>

This will display “Harry Potter” as the default value in the prompt so if the user just presses OK without changing anything, we will get:

Welcome Harry Potter!

(If the user presses Cancel, you will still get “null”).

If you would like to ensure that the value is not a “null” by the user hitting Cancel, and also trap the case where the user enters an empty string (covered above), you can try something like:

<script>
  do {
    var myname = prompt("What is your name?", "Harry Potter")
  } while (myname === null || myname .length == 0)
  document.write("Welcome " + myname + "!<BR>")
</script>

Here, the prompt box will be adamant and refuse to accept either an empty input or a “cancel” input. You will have to enter some text and only then exit the do..while loop at which point the name you entered will be printed in the HTML page.

Getting user input via a textbox

The second way to obtain user input is via a form with textboxes. In the code below, we are using a form to obtain two numbers as input from the user and then we will print their sum. We set up two textfields with names that we can refer to the underlying elements.

<body>
<H2>Your Personal Adder</H2>
<form><br>
  Enter your First Number: <input type="text" id="number1" /><br><br>
  Enter your Second Number: <input type="text" id="number2" /><br><br>
  <input type="submit" value="Submit" onclick="adder()" /><br>
</form>
<script>
  function adder() {
    var num1 = document.getElementById("number1").value
    var num2 = document.getElementById("number2").value
    document.write("<h1>Results</h1>")
    document.write(num1 + " + " + num2 + " = " 
         + (parseInt(num1) + parseInt(num2)) + "<BR>")
  }
</script>
</body>

First, we setup a form with two input text fields with ids “number1” and “number2”. When we click the Submit button the adder() function is invoked. Inside the adder() function, we retrieve the elements (specifically, their values). Then we add them (taking care to parse them as integers) and print the sum.

The main form looks like (with sample inputs of 23 and 46):

How to get user input in Javascript

The output is, as expected:

How to get user input in Javascript

If you liked learning about gathering user input, checkout our blogpost on NaNs which is important when you desire to validate user input. Also see our blogpost on how not to allow special characters to be typed in a textbox while gathering user input.

If you liked this blogpost and manipulating strings, checkout our blogpost on how to check if a letter is uppercase in Javascript.

Want to learn Javascript with us? Sign up for 1:1 or small group classes.

Kodeclik sidebar newsletter

Join our mailing list

Subscribe to get updates about our classes, camps, coupons, and more.

About

Kodeclik is an online coding academy for kids and teens to learn real world programming. Kids are introduced to coding in a fun and exciting way and are challeged to higher levels with engaging, high quality content.

Copyright @ Kodeclik 2024. All rights reserved.