Page 167 - Computer Software Application TP - Volume 1
P. 167
COMPUTER SOFTWARE APPLICATION - CITS
TASK 2: Form Validation
1 Open the text editor
2 Write the following codes
<html>
<head></head>
<body>
<form id=”myForm”>
<label for=”username”>Username:</label>
<input type=”text” id=”username” name=”username”>
<button type=”submit”>Submit</button>
</form>
<script>
const form = document.getElementById(“myForm”);
form.addEventListener(“submit”, handleSubmit);
function handleSubmit(event) {
event.preventDefault();
const username = document.getElementById(“username”).value;
if (username === “”) {
alert(“Please enter a username”);
return; // Prevent form submission
}
console.log(“Submitted username:”, username);
}
</script>
</body>
</html>
3 Save the program as a .html file
4 Open the html file with a web browser
5 Go to the browsers console tab and verify the output.
152
CITS : IT & ITES - Computer Software Application - Exercise 42