User input with forms

We will now start using forms to take user input. Forms include elements such as input text boxes, checkboxes, radio buttons, drop-down lists, and submit buttons.

In this tutorial, we will ask the user to enter their name and then display a personalised welcome message with their name included. In the first example, we will do do just that. In the second example, we will also hide the form once the user has entered and submitted their name.

Watch the video below and then scroll down to see the code.

Here is the code for the first example, where we ask for the user’s name and display a personalised welcome message. Notice that the form still remains after it has been submitted.

<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="utf-8"/>
 <title>JavaScript - Forms</title>
 <script type="text/javascript">
 // This tutorial requires a basic understanding of forms in HTML
 // The form is created in the body section of the HTML page.
 
 function writeName(){
 var welcomeMsg = document.getElementById('welcome');
 var name = document.getElementById('name');
 
 welcomeMsg.innerHTML = "Welcome "+name.value+".<br/>";
 // We append .value to the end of name so that it sets the variable name
 // to be equal to a property which is the value, not the object.
 
 }
 
 </script>
 
</head>
<body>
 
<p id="welcome"></p>
<form>
 What is your name:<input type="text" id="name"/><br/>
 <input type="button" value="Submit" onclick="writeName();"/>
</form>
 
</body>
</html>

In the second example (below), once the user has entered their name and clicked on the ‘Submit’ button, the personalised message will be displayed and the form will also disappear.

<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="utf-8"/>
 <title>JavaScript - Forms</title>
 <script type="text/javascript">
 // This tutorial requires a basic understanding of forms in HTML
 // The form is created in the body section of the HTML page.
 
 function writeName(){
 var welcomeMsg = document.getElementById('welcome');
 var name = document.getElementById('name');
 var formContent = document.getElementById('entername');
 
 welcomeMsg.innerHTML = "Welcome "+name.value+".<br/>";
 // We append .value to the end of name so that it sets the variable name
 // to be equal to a property which is the value, not the object.
 
 formContent.innerHTML = ""; // this removes the form text input box after name has been entered.
 
 }
 
 </script>
 
</head>
<body>
 
<p id="welcome"></p>
<form id="entername">
 What is your name:<input type="text" id="name"/><br/>
 <input type="button" value="Submit" onclick="writeName();"/>
</form>
 
</body>
</html>

Next tutorial: Treating text input from a form as an integer of float