Professional Documents
Culture Documents
Tutorial J5
Tutorial J5
Aim: To learn about basic JavaScript and using functions and conditional statements
1. Draw a flow chart for a JavaScript program to check a person’s username and password:
Start
Insert Username
and password
End
Open a text editor of your choice, such as Notepad (on Windows) or TextEdit (on a Mac). Create
an HTML page leaving space between <body> and </body> tags. Between the <body> and
</body> tags add the <script> and </script> tags.
<!DOCTYPE html>
<html>
<body>
<script>
var userID
var password
var ReturnValue
</script>
</body>
</html>
4. Amend the code above to use a function to validate the username and password.
<!DOCTYPE html>
<html>
<body>
<script>
var userID
var password
var ReturnValue
function validate()
{
alert('Valid Logon');
}
else
{
alert('Invalid Logon');
}
</script>
</body>
</html>
5. Using switch statements. Try out the code below to understand the use of switch:
6. Now let’s say we want to improve the earlier program by giving the following messages:
Case 1: Valid logon (username and password correct)
Case 2: Invalid logon - Username correct, password wrong
Case 3: Invalid logon - Username wrong, password correct
Case 4: Invalid logon - Both username and password wrong
Using the following switch statements improve your program to display the messages.
switch (valid)
{
case 1:
alert('Valid Logon')
break
case 2:
alert('Valid User ID. Invalid Password.')
break
case 3:
alert('Invalid user ID. Valid Password.')
break
case 4:
alert('Invalid User ID and Password')
break
<script>
var userID
var password
var ReturnValue
switch (true)
{
case(userID == 'ScoobyDoo' && password == 'blackpink'): alert("Valid Logon")
break;
case(userID == 'ScoobyDoo' && password!== 'blackpink'): alert("Valid User ID.Invalid Password")
break;
case(userID !== 'ScoobyDoo' && password == 'blackpink'): alert("Invalid Use ID")
break;
case(userID !== 'ScoobyDoo' && password !== 'blackpink'): alert("Invalid User ID and password")
break;
}
</script>
</body>
</html>
References:
1. https://www.w3schools.com/js/default.asp
2. https://www.w3schools.com/js/js_functions.asp
3. https://www.w3schools.com/js/js_switch.asp
4. JavaScript Demystified, Chapter 5 by Jim Keogh