Assignments Of Day 24
JavaScript and Forms
Assignment
1: Basic Form Access
Problem:
Create a form with the following fields:
- Username
(text input)
- Password
(password input)
- A
submit button
Using JavaScript, print the
values of the fields in the console when the user clicks the submit button.
Prevent the default form submission.
Solution:
html
Copy code
<form id="loginForm">
<label for="username">Username:</label>
<input type="text" id="username"
name="username">
<label for="password">Password:</label>
<input type="password" id="password"
name="password">
<button type="submit">Login</button>
</form>
<script>
document.getElementById("loginForm").addEventListener("submit",
function(event) {
event.preventDefault(); // Prevent default
submission
let username = document.getElementById("username").value;
let password = document.getElementById("password").value;
console.log("Username:", username);
console.log("Password:", password);
});
</script>
Assignment
2: Form Validation
Problem:
Create a form with the following fields:
- Email
(text input)
- Password
(password input)
- Submit
button
Add validation rules:
1. The email
field must contain an "@" symbol.
2. The
password must be at least 6 characters long.
Display appropriate error messages using alert() if the validation fails.
Solution:
html
Copy code
<form id="registrationForm">
<label for="email">Email:</label>
<input type="text" id="email"
name="email">
<label for="password">Password:</label>
<input type="password" id="password"
name="password">
<button type="submit">Register</button>
</form>
<script>
document.getElementById("registrationForm").addEventListener("submit",
function(event) {
let email = document.getElementById("email").value;
let password = document.getElementById("password").value;
// Validate email
if (!email.includes("@")) {
alert("Please enter a valid email
address.");
event.preventDefault(); // Prevent
submission
return;
}
// Validate password
if (password.length < 6) {
alert("Password must be at least 6
characters long.");
event.preventDefault(); // Prevent
submission
}
});
</script>
Assignment
3: Multi-field Form Validation
Problem:
Create a form with the following fields:
- Full
Name (text input)
- Age
(number input)
- Feedback
(textarea)
- Submit
button
Validation rules:
1. Full Name
should not be empty.
2. Age
should be greater than 0.
3. Feedback
should have at least 10 characters.
If any validation fails, display
an alert with the error message and prevent form submission.
Solution:
html
Copy code
<form id="feedbackForm">
<label for="fullName">Full
Name:</label>
<input type="text" id="fullName"
name="fullName">
<label for="age">Age:</label>
<input type="number" id="age"
name="age">
<label for="feedback">Feedback:</label>
<textarea id="feedback" name="feedback"></textarea>
<button type="submit">Submit</button>
</form>
<script>
document.getElementById("feedbackForm").addEventListener("submit",
function(event) {
let fullName = document.getElementById("fullName").value.trim();
let age = parseInt(document.getElementById("age").value);
let
feedback = document.getElementById("feedback").value.trim();
if (fullName === "") {
alert("Full Name cannot be
empty.");
event.preventDefault();
return;
}
if (isNaN(age) || age <= 0) {
alert("Age must be a positive
number.");
event.preventDefault();
return;
}
if (feedback.length < 10) {
alert("Feedback must be at least 10
characters long.");
event.preventDefault();
}
});
</script>
Assignment
4: Prevent Default and Submit Data
Problem:
Create a login form with the following fields:
- Username
(text input)
- Password
(password input)
- A
checkbox to agree to terms
- A
submit button
Validation rules:
1. Both
username and password should not be empty.
2. The user
must check the terms checkbox before submitting.
If all validations pass, display a success message in the console.
Solution:
html
Copy code
<form id="loginForm">
<label for="username">Username:</label>
<input type="text" id="username"
name="username">
<label for="password">Password:</label>
<input type="password" id="password"
name="password">
<label>
<input type="checkbox" id="terms"
name="terms">
I agree to the terms and conditions
</label>
<button type="submit">Login</button>
</form>
<script>
document.getElementById("loginForm").addEventListener("submit",
function(event) {
let username = document.getElementById("username").value.trim();
let password = document.getElementById("password").value.trim();
let terms = document.getElementById("terms").checked;
if (username === "" || password ===
"") {
alert("Both fields are required!");
event.preventDefault();
return;
}
if (!terms) {
alert("You must agree to the terms and
conditions!");
event.preventDefault();
return;
}
console.log("Form submitted
successfully!");
});
</script>
These assignments reinforce the
understanding of form interaction, validation, and submission handling in
JavaScript.
4o
You said:
give some more
ChatGPT
said:
ChatGPT
Additional
Assignments on JavaScript and Forms
Assignment
5: Dynamic Error Messages
Problem:
Create a form with the following fields:
- Name
(text input)
- Email
(text input)
- Password
(password input)
- Submit
button
Validation rules:
1. Name
should not be empty.
2. Email
must contain "@" and a domain.
3. Password
must be at least 8 characters long.
Instead of using alert(),
dynamically display error messages below the respective input fields if the
validation fails.
Solution:
html
Copy code
<form id="dynamicForm">
<label for="name">Name:</label>
<input type="text" id="name"
name="name">
<p id="nameError" style="color:
red;"></p>
<label for="email">Email:</label>
<input type="text" id="email"
name="email">
<p id="emailError" style="color:
red;"></p>
<label for="password">Password:</label>
<input type="password" id="password"
name="password">
<p id="passwordError" style="color:
red;"></p>
<button type="submit">Submit</button>
</form>
<script>
document.getElementById("dynamicForm").addEventListener("submit",
function(event) {
let name = document.getElementById("name").value.trim();
let email = document.getElementById("email").value.trim();
let password = document.getElementById("password").value.trim();
let isValid = true;
document.getElementById("nameError").innerText
= "";
document.getElementById("emailError").innerText
= "";
document.getElementById("passwordError").innerText
= "";
if (name === "") {
document.getElementById("nameError").innerText
= "Name is required.";
isValid = false;
}
if (!email.includes("@") || !email.includes("."))
{
document.getElementById("emailError").innerText
= "Please enter a valid email address.";
isValid = false;
}
if (password.length < 8) {
document.getElementById("passwordError").innerText
= "Password must be at least 8 characters long.";
isValid = false;
}
if (!isValid) {
event.preventDefault();
}
});
</script>
Assignment
6: Real-Time Validation
Problem:
Create a registration form with a password and a confirm password field.
- As
the user types in the confirm password field, check if it matches the
password field.
- Display
a real-time message below the confirm password field indicating whether
the passwords match.
Solution:
html
Copy code
<form id="realTimeForm">
<label for="password">Password:</label>
<input type="password" id="password"
name="password">
<label for="confirmPassword">Confirm
Password:</label>
<input type="password" id="confirmPassword"
name="confirmPassword">
<p id="passwordMatch" style="color:
red;"></p>
<button type="submit">Register</button>
</form>
<script>
document.getElementById("confirmPassword").addEventListener("input",
function() {
let password = document.getElementById("password").value;
let confirmPassword = document.getElementById("confirmPassword").value;
let message = document.getElementById("passwordMatch");
if (confirmPassword === "") {
message.innerText = "";
} else if (password === confirmPassword) {
message.innerText = "Passwords
match!";
message.style.color = "green";
} else {
message.innerText = "Passwords do not match.";
message.style.color = "red";
}
});
</script>
Assignment
7: Dropdown Validation
Problem:
Create a form with the following fields:
- Name
(text input)
- Country
(dropdown with options: Select, USA, Canada, India)
- Submit
button
Validation rules:
1. Name
cannot be empty.
2. A country
must be selected (not "Select").
If the validation fails, display
error messages above the submit button.
Solution:
html
Copy code
<form id="dropdownForm">
<label for="name">Name:</label>
<input type="text" id="name"
name="name">
<label for="country">Country:</label>
<select id="country" name="country">
<option value="Select">Select</option>
<option value="USA">USA</option>
<option value="Canada">Canada</option>
<option value="India">India</option>
</select>
<p id="formError" style="color:
red;"></p>
<button type="submit">Submit</button>
</form>
<script>
document.getElementById("dropdownForm").addEventListener("submit",
function(event) {
let name = document.getElementById("name").value.trim();
let country = document.getElementById("country").value;
let error = document.getElementById("formError");
error.innerText = "";
if (name === "" || country === "Select")
{
error.innerText = "Name and country
selection are required.";
event.preventDefault();
}
});
</script>
Assignment
8: Length-Restricted Input
Problem:
Create a form with a text input for a "Username" and a character
counter below the input. The username must not exceed 15 characters. Display
the remaining characters in real-time as the user types.
Solution:
html
Copy code
<form id="lengthForm">
<label for="username">Username
(Max 15 characters):</label>
<input type="text" id="username"
name="username" maxlength="15">
<p id="charCount">15
characters remaining</p>
<button type="submit">Submit</button>
</form>
<script>
document.getElementById("username").addEventListener("input",
function() {
let maxLength = 15;
let currentLength = this.value.length;
let remaining = maxLength - currentLength;
document.getElementById("charCount").innerText
= `${remaining} characters remaining`;
});
</script>
These assignments cover a variety
of form-related tasks to give students hands-on experience with JavaScript
validation and DOM manipulation techniques.
4o
You said:
give some more
ChatGPT
said:
ChatGPT
Additional
Assignments on JavaScript and Forms
Assignment
9: Disable Submit Button Until Form is Valid
Problem:
Create a login form with two fields:
- Email
- Password
Add a "Log In" button
that is initially disabled. The button should be enabled only when both fields
are valid:
- Email
must include "@" and "."
- Password
must be at least 6 characters long.
Solution:
html
Copy code
<form id="loginForm">
<label for="email">Email:</label>
<input type="text" id="email"
name="email">
<label for="password">Password:</label>
<input type="password" id="password"
name="password">
<button type="submit" id="loginButton"
disabled>Log In</button>
</form>
<script>
const
emailInput = document.getElementById("email");
const
passwordInput = document.getElementById("password");
const
loginButton = document.getElementById("loginButton");
function validateForm()
{
const email = emailInput.value.trim();
const password = passwordInput.value.trim();
if (email.includes("@") &&
email.includes(".") && password.length >= 6) {
loginButton.disabled = false;
} else {
loginButton.disabled = true;
}
}
emailInput.addEventListener("input",
validateForm);
passwordInput.addEventListener("input",
validateForm);
</script>
Assignment
10: Conditional Input Fields
Problem:
Create a form with the following fields:
1. Are you a
student? (Yes/No - radio buttons)
2. Student
ID field
(only visible if the user selects "Yes").
3. A
"Submit" button.
Ensure that the Student ID field
is required only if the user selects "Yes".
Solution:
html
Copy code
<form id="studentForm">
<p>Are you a student?</p>
<label><input type="radio"
name="isStudent" value="yes"> Yes</label>
<label><input type="radio"
name="isStudent" value="no"> No</label>
<div id="studentIdField" style="display:
none;">
<label for="studentId">Student
ID:</label>
<input type="text" id="studentId"
name="studentId">
</div>
<button type="submit">Submit</button>
</form>
<script>
const
isStudentRadios = document.getElementsByName("isStudent");
const
studentIdField = document.getElementById("studentIdField");
const
studentIdInput = document.getElementById("studentId");
isStudentRadios.forEach(radio
=> {
radio.addEventListener("change", function()
{
if (this.value === "yes") {
studentIdField.style.display = "block";
studentIdInput.required = true;
} else {
studentIdField.style.display = "none";
studentIdInput.required = false;
}
});
});
</script>
Assignment
11: Age Validation with Dynamic Feedback
Problem:
Create a form with the following:
1. Name
(text input).
2. Age
(number input).
Display a dynamic message:
- If
age is less than 18, show "You must be 18 or older to register."
- If
age is 18 or above, show "Age verified."
Solution:
html
Copy code
<form id="ageForm">
<label for="name">Name:</label>
<input type="text" id="name"
name="name">
<label for="age">Age:</label>
<input type="number" id="age"
name="age">
<p id="ageMessage"
style="color: red;"></p>
<button type="submit">Submit</button>
</form>
<script>
document.getElementById("age").addEventListener("input",
function() {
const age = parseInt(this.value, 10);
const message = document.getElementById("ageMessage");
if (isNaN(age) || age < 18) {
message.innerText = "You must be 18 or
older to register.";
message.style.color = "red";
} else {
message.innerText = "Age
verified.";
message.style.color = "green";
}
});
</script>
Assignment
12: Auto Format Phone Number
Problem:
Create a form with a phone number input. As the user types, automatically
format the number in the (XXX) XXX-XXXX format.
Solution:
html
Copy code
<form id="phoneForm">
<label for="phone">Phone
Number:</label>
<input type="text" id="phone"
name="phone" maxlength="14" placeholder="(XXX)
XXX-XXXX">
<button type="submit">Submit</button>
</form>
<script>
document.getElementById("phone").addEventListener("input",
function() {
let value = this.value.replace(/\D/g, "");
// Remove non-numeric characters
if (value.length > 3) value = `(${value.slice(0,
3)}) ${value.slice(3)}`;
if (value.length > 9) value = `${value.slice(0,
9)}-${value.slice(9)}`;
this.value = value;
});
</script>
Assignment
13: Dynamic Form Fields
Problem:
Create a form where users can dynamically add multiple "Skill" input
fields by clicking an "Add Skill" button.
Solution:
html
Copy code
<form id="skillForm">
<div id="skillsContainer">
<label for="skill1">Skill
1:</label>
<input type="text" id="skill1"
name="skills[]">
</div>
<button type="button" id="addSkill">Add
Skill</button>
<button type="submit">Submit</button>
</form>
<script>
let
skillCount = 1;
document.getElementById("addSkill").addEventListener("click",
function() {
skillCount++;
const skillsContainer = document.getElementById("skillsContainer");
const newSkill = document.createElement("div");
newSkill.innerHTML = `<label
for="skill${skillCount}">Skill ${skillCount}:</label>
<input
type="text" id="skill${skillCount}"
name="skills[]">`;
skillsContainer.appendChild(newSkill);
});
</script>
These assignments provide diverse
challenges to help students gain practical experience with form manipulation
and validation using JavaScript.
