0% found this document useful (0 votes)
63 views15 pages

Download

1. The document describes creating an HTML form and using JavaScript to validate user input on the form. 2. It instructs the reader to create a basic form with name and email fields, then add JavaScript code using the <script> tag to define a function that validates the form inputs. 3. The validation function accesses the form elements using their IDs, checks if the name field is blank, and displays an error alert if so to prompt the user to enter a name.

Uploaded by

yahya bennis
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
63 views15 pages

Download

1. The document describes creating an HTML form and using JavaScript to validate user input on the form. 2. It instructs the reader to create a basic form with name and email fields, then add JavaScript code using the <script> tag to define a function that validates the form inputs. 3. The validation function accesses the form elements using their IDs, checks if the name field is blank, and displays an error alert if so to prompt the user to enter a name.

Uploaded by

yahya bennis
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 15

28/10/2023 12:35 about:blank

Lab: Validating a JavaScript form

Estimated time 45 minutes

JavaScript is a client-side scripting language and is commonly used to create dynamic web pages. It helps you change web page content dynamically, as well as
enables you to validate forms and perform other actions. In this lab, you will create an HTML form that uses JavaScript to validate input.

Objectives
After completing this lab, you will be able to:

1. Create a basic web form


2. Use the <script> tag
3. Add a JavaScript function
4. Access the form controls from JavaScript
5. Access a textbox and check if it is blank
6. Execute a set of statements based on a condition
7. Display error messages
8. Execute a function when the form is submitted
9. Practice Exercise: Add Javascript interactivity to the Hands-on Lab: Unit Conversion using HTML5 Structural Elements (completed earlier)

1. Create an HTML form


In this exercise, you will create a simple form that accepts a person’s name and email address and then performs a simple validation on the entered input.

On the window to the right, click on File > New File. A New File window opens. Enter form_validation.html as the file name and click OK. You are now ready to
start creating the new form.

Let’s start by creating a simple form designed to accept the user’s name and email address. The form will have a Submit button and a Reset button.

Copy and paste the following code into your file to create the initial form without validation:

1. 1
2. 2
3. 3
4. 4
5. 5
6. 6
7. 7
8. 8
9. 9
10. 10
11. 11
12. 12
13. 13
14. 14
15. 15
16. 16
17. 17
18. 18
19. 19

1. <!DOCTYPE html>
2. <html>
3. <head>
4. <title>Contact Details</title>
5. </head>
6. <body>
7. <h2>Enter your contact details:</h2> <br>
8. <form id="form1">
9. <label for="name">Name:</label>
10. <input type="text" id="name" name="name">
11. <br><br>
12. <label for="email">Email Address:</label>
13. <input type="text" id="email" name="email">
14. <br><br>
15. <input type="submit" value="Submit">
16. <input type="reset" value="Reset">
17. </form>
18. </body>
19. </html>

Copied!

When you have pasted the code, save your file. To see how your HTML page will be displayed, you can use the built-in Live Server extension by following the
instructions below.

about:blank 1/15
28/10/2023 12:35 about:blank
1. Open the file explorer and navigate to your file.

2. 1. 1
1. Right click on your file & click on ‘Open with Live Server’
Copied!

about:blank 2/15
28/10/2023 12:35 about:blank

3. 1. 1
1. This should show a notification mentioning that the server has started on port 5500.
Copied!

about:blank 3/15
28/10/2023 12:35 about:blank

4. 1. 1
1. Click on the Skills Network button on the left, it will open the "Skills Network Toolbox". Then click the Other then Launch App
Copied!

about:blank 4/15
28/10/2023 12:35 about:blank

5. 1. 1
1. Click on the Skills Network button on the left to open the "Skills Network Toolbox". Click "Other" then "Launch Application". F
Copied!

6. 1. 1

about:blank 5/15
28/10/2023 12:35 about:blank
1. Click on the file name to view its preview.
Copied!

After following the above steps, Your page should look like this:

2. Use the <script> tag


We use the <script> tag to embed executable code, usually JavaScript, into an HTML page. The tag can contain scripting statements, or it can refer to an external
script file. We use a type attribute to specify the scripting language.

Although you can put the <script> tag anywhere in your HTML document, for this lab you’ll put it in the <head> section.

Replace the <head> section of your file with the following code. It tells the browser that the code we are about to put inside the <script> tag must be executed as
JavaScript.
1. 1
2. 2
3. 3
4. 4
5. 5

1. <head>
2. <script type="application/javascript">
3. </script>
4. <title>Contact Details</title>
5. </head>

Copied!

about:blank 6/15
28/10/2023 12:35 about:blank

3. Add a JavaScript function


Now you’ll specify what happens when a user clicks the Submit button. We specify this behavior with a user-defined JavaScript function, which is a block of code
that is executed when it’s called. A function can be called any number of times.

A function in JavaScript looks like this:


1. 1
2. 2
3. 3
4. 4

1. function functon_name()
2. {
3. // code goes here
4. }

Copied!

Let’s add an empty function that has the name checkdata. We will use this to validate the data in the form. Replace the <script> tags in your file with the following
code:
1. 1
2. 2
3. 3
4. 4
5. 5

1. <script type="application/javascript">
2. function checkdata()
3. {
4. }
5. </script>

Copied!

4. Access HTML controls within JavaScript


The function you’ve created is intended to validate the contents of each of the input elements in the form. To access the data for an element, the script needs to refer
to the correct element.

One way to identify an element is to use a method called getElementByID(elementID). The following line of code returns the element with the ID name:
1. 1

1. document.getElementByID("name");

Copied!

The following lines of code enable you to access the name and email input elements of the form. Note that the id’s of both these elements have already been specified
in the HTML code. We will store the references to the elements in two JavaScript variables named username and emailid.

1. 1
2. 2

1. var username = document.getElementById("name");


2. var emailid = document.getElementById("email");

Copied!

Copy the aabove code and paste it into your checkdata() function.

5. Access and check data


When the references to the elements are stored in the variables, the values of the elements can be retrieved using the value attribute. If username is the variable that
contains the input element’s reference, then its value can be accessed using
username.value

To check if this value is blank, we can use the following statement:


username.value == ""

"" indicates an empty string.

6. Execute a set of statements based on a condition


If the value is blank, we will print an error message and return the focus back to the empty element.

To perform this action, we use a JavaScript conditional statement called the if statement. The if conditional statement allows us to specify a block of code to be
executed if a condition is true.

The syntax of the statement is as follows:


1. 1
2. 2
3. 3

1. if(condition){
2. //block of code to be executed, if the condition is true.
3. }

Copied!

about:blank 7/15
28/10/2023 12:35 about:blank
Let’s check if the username value is empty by using an if statement. Copy this code and paste it at the bottom of your checkdata() function:
1. 1
2. 2
3. 3

1. if(username.value==""){
2. return false;
3. }

Copied!

If the value is blank, the return false; statement returns a boolean value false from the checkdata() function that we added in step 3.

We will check all input elements of the form in this way to determine whether they are empty.

7. Display error messages


You can display a message to a user with the help of a pop-up alert message box. To do this, you will use the alert method.

Let’s use this method within the function to alert the user.
1. 1
2. 2
3. 3
4. 4
5. 5

1. if(username.value==""){
2. alert("Please enter the name");
3. username.focus();
4. return false;
5. }

Copied!

The username.focus() statement is used to bring the input focus back to the element where we found a problem, in this case, username.

Replace the current conditional in your function with this new code. Below, try to add the same conditional logic, but for the email_address element instead.

Next, we will indicate that none of the elements are blank by returning true. So, we need to add a return true statement at the end of the function.

It’s a good practice to include comments in your code. Comments will help you and other programmers easily debug any errors that we might encounter while
running the code. In JavasScript, we add single-line comments using two forward slashes: //

Our final checkdata() function with comments added looks like:


1. 1
2. 2
3. 3
4. 4
5. 5
6. 6
7. 7
8. 8
9. 9
10. 10
11. 11
12. 12
13. 13
14. 14
15. 15
16. 16
17. 17
18. 18
19. 19
20. 20

1. function checkdata(){
2. //Create references to the input elements we wish to validate
3. var username = document.getElementById("name");
4. var email_address = document.getElementById("email");
5.
6. //Check if username field is empty
7. if(username.value == ""){
8. alert("Please enter the name");
9. username.focus();
10. return false;
11. }
12. //Check if email field is empty
13. if(email_address.value == ""){
14. alert("Please enter the email");
15. email_address.focus();
16. return false;
17. }
18. //If all is well return true.
19. return true;
20. }

Copied!

This function should now work as expected and is now ready to be called, so we can use it wherever we need.

8. Execute a function when the form is submitted


Now that we have a working checkdata() function, our final step is to call it whenever the form is submitted. We do this using the onsubmit event in our HTML
code. This event will be triggered when users click the Submit button.

about:blank 8/15
28/10/2023 12:35 about:blank
The following code links the onsubmit event to the checkdata() function:
1. 1

1. <form id="form1" onsubmit="return checkdata()">

Copied!

{:codeblock}

This code ensures that the checkdata() function is invoked every time the form is submitted.

Following is the complete code along with the HTML form and JavaScript validation function. Copy and paste the code into your file and check it to determine if it
is properly validating:
1. 1
2. 2
3. 3
4. 4
5. 5
6. 6
7. 7
8. 8
9. 9
10. 10
11. 11
12. 12
13. 13
14. 14
15. 15
16. 16
17. 17
18. 18
19. 19
20. 20
21. 21
22. 22
23. 23
24. 24
25. 25
26. 26
27. 27
28. 28
29. 29
30. 30
31. 31
32. 32
33. 33
34. 34
35. 35
36. 36
37. 37
38. 38
39. 39
40. 40
41. 41

1. <!DOCTYPE html>
2. <html>
3. <head>
4. <title>Contact Details</title>
5. <script type="application/javascript">
6. function checkdata(){
7. //Create references to the input elements we wish to validate
8. var username = document.getElementById("name");
9. var email_address = document.getElementById("email");
10.
11. //Check if username field is empty
12. if(username.value == ""){
13. alert("Please enter the name");
14. username.focus();
15. return false;
16. }
17. //Check if email field is empty
18. if(email_address.value == ""){
19. alert("Please enter the email");
20. email_address.focus();
21. return false;
22. }
23. //If all is well return true.
24. return true;
25. }
26. </script>
27. </head>
28. <body>
29. <h2>Enter your contact details:</h2> <br>
30. <form id="form1" onsubmit="return checkdata()">
31. <label for="name">Name:</label>
32. <input type="text" id="name" name="name">
33. <br><br>
34. <label for="email">Email Address:</label>
35. <input type="text" id="email" name="email">
36. <br><br>
37. <input type="submit" value="Submit">
38. <input type="reset" value="Reset">
39. </form>
40. </body>
41. </html>

Copied!

about:blank 9/15
28/10/2023 12:35 about:blank

Practice Exercise: Add Javascript interactivity to a HTML page through links


You would have created a web page for Unit Conversion in a file named index.html and styled it with CSS in the lab Hands-on Lab: Styling your Web Page
using CSS earlier. If not, click here to complete it

Now you will add event listeners to the buttons in the web page, to make them functional.

1. Click on the button below to create a new file named script.js.

Open script.js in IDE

2. Add the function to convert temparature from Celsius to Fahrenheit

It should fetch the value inside the “celsius” element in index.html

The mathematical formula for conversion should be applied


1. 1

1. Temp(Fahrenheit) = [Temp(Degrees)*9/5] + 32

Copied!

Set the innerHTML property of the “fahrenheit” element in index.html to the returned value

Click here to see the code

3. Add the function to convert weight from Kgs to Pounds

It should fetch the value inside the “kilo” element in index.html

The mathematical formula for conversion should be applied

1. 1

1. Weight(Pounds) = Weight(Kgs) * 2.2

Copied!

Set the innerHTML property of the “pounds” element in index.html to the returned value

Click here to see the code

4. Add the function to convert distance from Kms to Miles

It should fetch the value inside the “km” element in index.html

The mathematical formula for conversion should be applied


1. 1

1. Distance(Miles) = Distance(Kms) * 0.62137

Copied!

Set the innerHTML property of the “miles” element in index.html to the returned value

Click here to see the code


1. 1
2. 2
3. 3
4. 4
5. 5
6. 6
7. 7

1. function distance(){
2. //To convert KMs to Miles
3. // KM * 0.62137
4. var km = document.getElementById("km").value;
5. var m = km * 0.62137
6. document.getElementById("miles").value = m
7. }

Copied!

5. Save the updated script.js.

Click here to see the completed code in script.js


1. 1
2. 2
3. 3
4. 4
5. 5
6. 6
7. 7
8. 8
9. 9

about:blank 10/15
28/10/2023 12:35 about:blank
10. 10
11. 11
12. 12
13. 13
14. 14
15. 15
16. 16
17. 17
18. 18
19. 19
20. 20
21. 21
22. 22
23. 23

1. function temperature(){
2. //To convert celcius to farenheit
3. //(CEL * 9/5) + 32
4. var c = document.getElementById("celsius").value;
5. var f = (c * 9/5) + 32
6. document.getElementById("fahrenheit").value = f
7. }
8.
9. function weight(){
10. //To convert KGs to Pounds
11. // KG * 2.2
12. var kg = document.getElementById("kilo").value;
13. var p = kg * 2.2
14. document.getElementById("pounds").value = p
15. }
16.
17. function distance(){
18. //To convert KMs to Miles
19. // KM * 0.62137
20. var km = document.getElementById("km").value;
21. var m = km * 0.62137
22. document.getElementById("miles").value = m
23. }

Copied!

6. Link style.css to index.html

Use the script tag with the src attribute.

Click to see the code


1. 1
2. 2
3. 3
4. 4
5. 5

1. <head>
2. <title>Document</title>
3. <link rel="stylesheet" href="style.css">
4. <script src="script.js"></script>
5. </head>

Copied!

7. Link the temperature section of index.html to the temperature function in script.js

To the button with ID temperature in index.html, add an onclick event to invoke the temperature() method.
Assign the ID value of temparature input to be ‘celsius’
Assign the ID value of temparature output to be ‘fahrenheit’

Click here to see the code


1. 1
2. 2
3. 3
4. 4
5. 5
6. 6
7. 7
8. 8
9. 9
10. 10
11. 11
12. 12
13. 13

1. <fieldset>
2. <legend>Temperature</legend>
3. <label for="Temperature">Celsius</label> <br/>
4.
5. <input type="number" id="celsius"> <br/>
6.
7. <button id="temperature" onclick="temperature()"> Convert </button> <br/>
8.
9. <input type="number" id="fahrenheit"> <br/>
10.
11. <label for="Temperature">Fahrenheit</label>
12. </fieldset>
13.

Copied!

8. Link the weight section of index.html to the weight function in script.js

To the button with ID weight in index.html, add an onclick event to invoke the weight() method.
about:blank 11/15
28/10/2023 12:35 about:blank
Assign the ID value of weight input to be ‘kilo’
Assign the ID value of weight output to be ‘pounds’

Click here to see the code


1. 1
2. 2
3. 3
4. 4
5. 5
6. 6
7. 7
8. 8
9. 9
10. 10
11. 11
12. 12

1. <fieldset>
2. <legend>Weight</legend>
3. <label for="Weight">KG</label> <br/>
4.
5. <input type="number" id="kilo"> <br/>
6.
7. <button id="weight" onclick="weight()"> Convert </button> <br/>
8.
9. <input type="number" id="pounds"> <br/>
10.
11. <label for="Weight">Pounds</label>
12. </fieldset>

Copied!

9. Link the distance section of index.html to the distance function in script.js

To the button with ID distance in index.html, add an onclick event to invoke the distance() method.
Assign the ID value of distance input to be ‘km’
Assign the ID value of distance output to be ‘miles’

Click to see the code


1. 1
2. 2
3. 3
4. 4
5. 5
6. 6
7. 7
8. 8
9. 9
10. 10
11. 11
12. 12

1. <fieldset>
2. <legend>Distance</legend>
3. <label for="Distance">KM</label> <br/>
4.
5. <input type="number" id="km"> <br/>
6.
7. <button id="distance" onclick="distance()"> Convert </button> <br/>
8.
9. <input type="number" id="miles"> <br/>
10.
11. <label for="Distance">Miles</label>
12. </fieldset>

Copied!

10. Save the code updated in index.html.

Click here to see the compelted code in index.html


1. 1
2. 2
3. 3
4. 4
5. 5
6. 6
7. 7
8. 8
9. 9
10. 10
11. 11
12. 12
13. 13
14. 14
15. 15
16. 16
17. 17
18. 18
19. 19
20. 20
21. 21
22. 22
23. 23
24. 24
25. 25
26. 26
27. 27
28. 28
29. 29

about:blank 12/15
28/10/2023 12:35 about:blank
30. 30
31. 31
32. 32
33. 33
34. 34
35. 35
36. 36
37. 37
38. 38
39. 39
40. 40
41. 41
42. 42
43. 43
44. 44
45. 45
46. 46
47. 47
48. 48
49. 49
50. 50
51. 51
52. 52
53. 53
54. 54
55. 55
56. 56
57. 57
58. 58
59. 59
60. 60
61. 61
62. 62
63. 63
64. 64
65. 65
66. 66
67. 67
68. 68
69. 69
70. 70
71. 71
72. 72
73. 73
74. 74
75. 75
76. 76
77. 77
78. 78
79. 79
80. 80
81. 81
82. 82
83. 83
84. 84
85. 85
86. 86
87. 87
88. 88
89. 89
90. 90
91. 91
92. 92
93. 93
94. 94
95. 95
96. 96
97. 97
98. 98
99. 99
100. 100
101. 101
102. 102
103. 103
104. 104
105. 105
106. 106
107. 107
108. 108
109. 109
110. 110
111. 111
112. 112
113. 113
114. 114
115. 115
116. 116
117. 117
118. 118
119. 119
120. 120
121. 121

1. <!DOCTYPE html>
2. <html lang="en">
3. <head>
4. <title>Document</title>
5. <link rel="stylesheet" href="style.css">
6. <script src="script.js"></script>
7. </head>
8. <body>
9. <section id="home">
10. <header>
11. Unit Conversions

about:blank 13/15
28/10/2023 12:35 about:blank
12. </header>
13. <nav>
14. <div class="topdiv">
15. <a href="#temperature"><button class="topmenu">Temperature</button></a>
16. <a href="#weight"><button class="topmenu">Weight</button></a>
17. <a href="#distance"><button class="topmenu">Distance</button></a>
18. </div>
19. </nav>
20. </section>
21. <div style="clear:both;"></div>
22.
23. <div id="all-conversion-sections">
24.
25. <section id="temperature" class="b temperature">
26. <div id="tmp">
27. <figure>
28. <img src="https://cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud/IBMDeveloperSkillsNetwork-CD0101EN-Skills
29. <figcaption>Celcius to Farenheit Conversion</figcaption>
30. </figure>
31. <article>
32.
33. <fieldset>
34. <legend>Temperature</legend>
35. <label for="Temperature">Celsius</label> <br/>
36.
37. <input type="number" id="celsius"> <br/>
38.
39. <button id="temperature" onclick="temperature()"> Convert </button> <br/>
40.
41. <input type="number" id="fahrenheit"> <br/>
42.
43. <label for="Temperature">Fahrenheit</label>
44. </fieldset>
45. <aside>
46. To convert celsuis to fahrenheit yourself, use this formula replacing the `C` with your temperature in celsuis: (C ×
47. </aside>
48. </article>
49. </div>
50. </section>
51.
52. <div style="clear:both;"></div>
53.
54. <section id="weight" class="b weight">
55. <div id="wgt">
56. <figure>
57. <img src="https://cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud/IBMDeveloperSkillsNetwork-CD0101EN-Skills
58. <figcaption>Kilograms to Pound Conversion</figcaption>
59. </figure>
60. <article>
61. <fieldset>
62. <legend>Weight</legend>
63. <label for="Weight">KG</label> <br/>
64.
65. <input type="number" id="kilo"> <br/>
66.
67. <button id="weight" onclick="weight()"> Convert </button> <br/>
68.
69.
70. <input type="number" id="pounds"> <br/>
71.
72. <label for="Weight">Pounds</label>
73. </fieldset>
74. <aside>
75. To convert kilograms to pounds yourself, use this formula replacing the `kg` with your weight in kilograms: kg x 2.2
76. </aside>
77. </article>
78. </div>
79. </section>
80.
81. <div style="clear:both;"></div>
82.
83. <section id="distance" class="b distance">
84. <div id="dst">
85. <figure>
86. <img src="https://cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud/IBMDeveloperSkillsNetwork-CD0101EN-Skills
87. <figcaption>Kilometers to Miles Conversion</figcaption>
88. </figure>
89. <article>
90. <fieldset>
91. <legend>Distance</legend>
92. <label for="Distance">KM</label> <br/>
93.
94. <input type="number" id="km"> <br/>
95.
96. <button id="distance" onclick="distance()"> Convert </button> <br/>
97.
98. <input type="number" id="miles"> <br/>
99.
100. <label for="Distance">Miles</label>
101. </fieldset>
102. <aside>
103. To convert kilometers to miles yourself, use this formula replacing the `km` with your distance in kilmeters: km &di
104. </aside>
105.
106. </article>
107. </div>
108. </section>
109. <div style="clear:both;"></div>
110.
111. </div>
112.
113. <div id="go-home" class="iconbutton">
114. <a href="#home">
115. <img src="https://cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud/IBMDeveloperSkillsNetwork-CD0101EN-SkillsNetwor

about:blank 14/15
28/10/2023 12:35 about:blank
116. </a>
117. </div>
118.
119. <footer>Learn more about HTML and CSS as a part of IBM Fullstack Cloud Developer Certification</footer>
120. </body>
121. </html>

Copied!

11. View index.html with Live Server and see if you get the converted temparature, weight and distance upon clicking the respective buttons.

Summary
Congratulations! You have now learned how to create a form and validate its user inputs. As a practice exercise, you have added Javascript interactivity to the Hands-
on Lab: Styling your Web Page using CSS to get the converted values of the Temparature, Weight & Distance metrics.

Tutorial details
Author: Ramesh Sannareddy

Other Contributor(s): Michelle Saltoun

Change log

Date Version Changed by Change Description


2020-08-13 1.0 Ramesh Sannareddy Initial version created
2022-09-01 1.1 Samaah Sarang Instructions changed
2022-10-17 1.2 Michelle Saltoun Minor changes
2022-11-07 1.3 Samaah Sarang JS for structural element lab added
2022-11-14 1.4 K Sundararajan Updated instructions based on SME review

© IBM Corporation 2020. All rights reserved.

about:blank 15/15

You might also like