Form Name Calculation Table Border 4 TR TD Input Type Text
Form Namecalctable Border4trtdinput Typetext
Develop a comprehensive HTML webpage that features a registration form with specific validation and interactive functionalities. The form must include fields for first and last name, student ID, biography, and a calculator with control buttons. Validation rules are strict: names must contain only letters with the first letter capitalized; student ID must be a 9-digit number; biography limited to 25 words. The calculator should accept numeric input, perform basic arithmetic, handle errors gracefully, and allow saving the result as 'Hours Worked This Week.' Submission must trigger validation, display summaries or errors accordingly, and prevent actual form submission. The entire implementation should embed CSS and JavaScript within the HTML file, following best practices with well-commented code and proper structure.
Paper For Above instruction
The task of creating a sophisticated registration form with embedded calculator and validation entails meticulous planning, detailed implementation, and adherence to best coding practices. This paper explores the design, development, and validation of such a web application, emphasizing usability, accessibility, and correctness.
Introduction
-------------
The primary goal of the project is to develop an interactive, validated registration form integrated with a calculator that can compute hours worked, in compliance with specified constraints. The webpage must be self-contained, with all style and script embedded, ensuring portability and ease of deployment. This paper details each component: form design, input validation, calculator functionality, error handling, and submission control.
Form Design
------------
The form includes five core inputs: First Name, Last Name, Student ID, Biography, and the Calculator interface. Each input must be clearly labeled, with user-friendly design considerations:
1. First and Last Name: Each uses a text input that accepts only alphabetic characters, with the first character capitalized. Validation occurs on input to prevent invalid characters.
2. Student ID: Requires a 9-digit numeric input, validated on input or on form submission.
3. Biography: A textarea allowing up to 25 words, count validated via JavaScript.
4. Calculator Section: Includes a display input field and 16 buttons for digits (0-9), operators (+, -, *, /), clear, and equals. An additional "Save" button transfers the current calculator result to a span labeled "Hours Worked This Week."
Implementation
--------------
The webpage structure employs semantic HTML5 elements, with embedded CSS for styling and JavaScript for functionality:
```html
/ Embedded CSS styles for layout, labels, inputs, error messages /
body {
font-family: Arial, sans-serif;
margin: 20px;
}
.error {
color: red;
font-weight: bold;
display: none;
}
formContainer.error {
background-color: #f8d7da; / light red for errors /
}
label {
display: block;
margin-top: 15px;
}
input[type="text"], textarea {
width: 300px;
padding: 5px;
}
calculator {
margin-top: 20px;
}
calcDisplay {
width: 160px;
height: 30px;
font-size: 16px;
text-align: right;
margin-bottom: 10px;
}
button {
width: 40px;
height: 40px;
margin: 2px;
font-size: 16px;
}
// JavaScript code for validation, calculator logic, event handling
document.addEventListener("DOMContentLoaded", function() {
const form = document.getElementById("registrationForm");
const firstName = document.getElementById("firstName");
const lastName = document.getElementById("lastName");
const studentID = document.getElementById("studentID");
const biography = document.getElementById("biography");
const hoursSpan = document.getElementById("hoursWorked");
const saveBtn = document.getElementById("saveBtn");
const calcDisplay = document.getElementById("calcDisplay");
const errorMsg = document.getElementById("errorMsg");
const formContainer = document.getElementById("formContainer");
let calcExpression = "";
let lastOperator = null;
let currentNumber = "";
let storedHours = "";
// Helper validation functions
function validateName(name) {
return /^[A-Z][a-zA-Z]*$/.test(name);
}
function validateStudentID(id) {
return /^\d{9}$/.test(id);
}
function validateBiography(bio) {
const words = bio.trim().split(/\s+/);
return words.length
}
// Input validation on blur
firstName.addEventListener("blur", function() {
if (!validateName(firstName.value.trim())) {
alert("First name must contain only letters and start with a capital letter.");
}
});
lastName.addEventListener("blur", function() {
if (!validateName(lastName.value.trim())) {
alert("Last name must contain only letters and start with a capital letter.");
}
});
studentID.addEventListener("blur", function() {
if (!validateStudentID(studentID.value.trim())) {
alert("Student ID must be exactly 9 digits.");
}
});
biography.addEventListener("input", function() {
if (!validateBiography(biography.value)) {
errorMsg.textContent = "Biography must be up to 25 words.";
errorMsg.style.display = "block";
} else {
errorMsg.style.display = "none";
}
});
// Calculator functions
function resetCalculator() {
calcDisplay.value = "";
calcExpression = "";
currentNumber = "";
}
function isNumeric(str) {
return !isNaN(str) && !isNaN(parseFloat(str));
}
document.querySelectorAll(".calcBtn").forEach(function(btn) {
btn.addEventListener("click", function() {
const val = this.value;
if (val === "C") {
resetCalculator();
} else if (val === "=") {
evaluateExpression();
} else if (["+", "-", "*", "/"].includes(val)) {
if (currentNumber !== "") {
calcExpression += currentNumber + " " + val + " ";
currentNumber = "";
} else if (calcExpression !== "") {
// Replace last operator if multiple operators pressed consecutively
calcExpression = calcExpression.trim().slice(0, -1) + val + " ";
}
} else { // Digit buttons
currentNumber += val;
calcDisplay.value = currentNumber;
}
});
});
function evaluateExpression() {
// Finalize currentNumber
if (currentNumber !== "") {
calcExpression += currentNumber;
}
try {
const result = eval(calcExpression);
if (isNaN(result) || !isFinite(result)) {
calcDisplay.value = "ERROR: press C";
} else {
calcDisplay.value = result;
}
} catch (e) {
calcDisplay.value = "ERROR: press C";
}
}
// Handle typing in calculator display
calcDisplay.addEventListener("input", function() {
if (isNumeric(this.value)) {
// valid number
currentNumber = this.value.trim();
} else {
// non-numeric input
this.value = "ERROR: press C";
currentNumber = "";
}
});
// "Save" button for hours
document.getElementById("saveBtn").addEventListener("click", function() {
const val = calcDisplay.value;
if (isNumeric(val)) {
storedHours = val;
hoursSpan.textContent = `Hours Worked This Week: ${storedHours}`;
} else {
// Display error message
errorMsg.textContent = "Invalid number of hours to save.";
errorMsg.style.display = "block";
setTimeout(() => { errorMsg.style.display = "none"; }, 3000);
}
});
// Form submission validation
form.addEventListener("submit", function(e) {
e.preventDefault(); // prevent actual submission
let errors = [];
// Validate first name
if (!validateName(firstName.value.trim())) {
errors.push("Invalid First Name.");
}
// Validate last name
if (!validateName(lastName.value.trim())) {
errors.push("Invalid Last Name.");
}
// Validate student ID
if (!validateStudentID(studentID.value.trim())) {
errors.push("Invalid Student ID.");
}
// Validate biography
if (!validateBiography(biography.value)) {
errors.push("Biography exceeds 25 words.");
}
// Additional validation can be added here
// Check calculator result
if (calcDisplay.value === "" || isNaN(calcDisplay.value)) {
errors.push("Calculator result is invalid.");
}
// If errors exist
if (errors.length > 0) {
// Show errors
formContainer.classList.add("error");
errorMsg.textContent = errors.join(" ");
errorMsg.style.display = "block";
} else {
// Clear errors and proceed
formContainer.classList.remove("error");
errorMsg.style.display = "none";
// Prepare summary alert
let summary = `Form Submission Successful!\n`;
summary += `First Name: ${firstName.value.trim()}\n`;
summary += `Last Name: ${lastName.value.trim()}\n`;
summary += `Student ID: ${studentID.value.trim()}\n`;
summary += `Biography: ${biography.value.trim()}\n`;
summary += `Calculator Result: ${calcDisplay.value}\n`;
if (storedHours !== "") {
summary += `Hours Worked This Week: ${storedHours}\n`;
}
alert(summary);
}
});
});