DOM Manipulation and Event Handling
DOM Manipulation and Event Handling
Task:
Create a webpage that initially displays a paragraph with the text "What's my name?" and
a button labeled "Reveal Name." When the button is clicked, the following actions should
occur:
• The paragraph text should change to "My name is [Your Name]!" (replace [Your
Name] with your actual name).
• The paragraph should be styled with a background color of gray.
• The button text should change to "Hide Name."
• If the button is clicked again, the paragraph text should revert to "What's my name?"
and the original styles should be removed, while the button text should change back
to "Reveal Name."
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>DOM Manipulation and Event Handling</title>
<style>
.gray-background {
background-color: gray;
color: white;
}
</style>
</head>
<body>
<p id="name-paragraph">What's my name?</p>
<button id="toggle-button">Reveal Name</button>
<script>
const paragraph = document.getElementById('name-paragraph');
const button = document.getElementById('toggle-button');
button.addEventListener('click', () => {
if (button.textContent === 'Reveal Name') {
paragraph.textContent = 'My name is [Your Name]!';
paragraph.classList.add('gray-background');
button.textContent = 'Hide Name';
} else {
paragraph.textContent = "What's my name?";
paragraph.classList.remove('gray-background');
button.textContent = 'Reveal Name';
}
});
</script>
</body>
</html>
Write a JavaScript program that performs form validation with the following requirements:
A. Form Fields:
o Full Name: Required field. Must not be empty.
o Email: Required field. Must be a valid email address.
o Username: Required field. Must not be empty.
o Password: Required field. Must be at least 8 characters long and include at
least one letter and one number.
o Confirm Password: Must match the password field.
o Date of Birth: Required field. The age should be between 18 and 99 years
old.
o Phone Number: Required field. Must be a valid Nepali phone number.
o Gender: Required field. Must select either "Male" or "Female".
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Form Validation</title>
</head>
<body>
<form id="myForm" onsubmit="return validateForm()">
<label for="fullName">Full Name:</label>
<input type="text" id="fullName" name="fullName"><br>
<label for="email">Email:</label>
<input type="email" id="email" name="email"><br>
<label for="username">Username:</label>
<input type="text" id="username" name="username"><br>
<label for="password">Password:</label>
<input type="password" id="password" name="password"><br>
<label for="gender">Gender:</label>
<select id="gender" name="gender">
<option value="">Select</option>
<option value="Male">Male</option>
<option value="Female">Female</option>
</select><br>
<script>
function validateForm() {
// Full Name
const fullName = document.getElementById('fullName').value;
if (fullName === '') {
alert('Full Name is required.');
return false;
}
// Email
const email = document.getElementById('email').value;
const emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
if (!emailPattern.test(email)) {
alert('Please enter a valid email address.');
return false;
}
// Username
const username = document.getElementById('username').value;
if (username === '') {
alert('Username is required.');
return false;
}
// Password
const password = document.getElementById('password').value;
const passwordPattern = /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{8,}$/;
if (!passwordPattern.test(password)) {
alert('Password must be at least 8 characters long and include at least one letter and one number.');
return false;
}
// Confirm Password
const confirmPassword = document.getElementById('confirmPassword').value;
if (password !== confirmPassword) {
alert('Passwords do not match.');
return false;
}
// Date of Birth
const dob = new Date(document.getElementById('dob').value);
const age = new Date().getFullYear() - dob.getFullYear();
if (age < 18 || age > 99) {
alert('Age must be between 18 and 99 years.');
return false;
}
// Phone Number
const phone = document.getElementById('phone').value;
const phonePattern = /^[9][6-9]\d{8}$/;
if (!phonePattern.test(phone)) {
alert('Please enter a valid Nepali phone number.');
return false;
}
// Gender
const gender = document.getElementById('gender').value;
if (gender === '') {
alert('Gender is required.');
return false;
}
Instructions:
o Create an HTML form with the above fields.
o Implement JavaScript to validate each field according to the requirements.
o Show error messages below each field in red if validation fails.
o Display a confirmation message on the same page if all validations pass.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Form Validation</title>
<style>
.error {
color: red;
}
.confirmation {
color: green;
}
</style>
</head>
<body>
<form id="myForm" onsubmit="return validateForm()">
<label for="fullName">Full Name:</label>
<input type="text" id="fullName" name="fullName"><br>
<span id="fullNameError" class="error"></span><br>
<label for="email">Email:</label>
<input type="email" id="email" name="email"><br>
<span id="emailError" class="error"></span><br>
<label for="username">Username:</label>
<input type="text" id="username" name="username"><br>
<span id="usernameError" class="error"></span><br>
<label for="password">Password:</label>
<input type="password" id="password" name="password"><br>
<span id="passwordError" class="error"></span><br>
<label for="gender">Gender:</label>
<select id="gender" name="gender">
<option value="">Select</option>
<option value="Male">Male</option>
<option value="Female">Female</option>
</select><br>
<span id="genderError" class="error"></span><br>
<script>
function validateForm() {
// Clear previous error messages
document.querySelectorAll('.error').forEach(element => element.textContent = '');
document.getElementById('confirmationMessage').textContent = '';
// Validate fields
let isValid = true;
// Full Name
const fullName = document.getElementById('fullName').value;
if (fullName === '') {
document.getElementById('fullNameError').textContent = 'Full Name is required.';
isValid = false;
}
// Email
const email = document.getElementById('email').value;
const emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
if (!emailPattern.test(email)) {
document.getElementById('emailError').textContent = 'Please enter a valid email address.';
isValid = false;
}
// Username
const username = document.getElementById('username').value;
if (username === '') {
document.getElementById('usernameError').textContent = 'Username is required.';
isValid = false;
}
// Password
const password = document.getElementById('password').value;
const passwordPattern = /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{8,}$/;
if (!passwordPattern.test(password)) {
document.getElementById('passwordError').textContent = 'Password must be at least 8 characters long and include at
least one letter and one number.';
isValid = false;
}
// Confirm Password
const confirmPassword = document.getElementById('confirmPassword').value;
if (password !== confirmPassword) {
document.getElementById('confirmPasswordError').textContent = 'Passwords do not match.';
isValid = false;
}
// Date of Birth
const dob = new Date(document.getElementById('dob').value);
const age = new Date().getFullYear() - dob.getFullYear();
if (age < 18 || age > 99) {
document.getElementById('dobError').textContent = 'Age must be between 18 and 99 years.';
isValid = false;
}
// Phone Number
const phone = document.getElementById('phone').value;
const phonePattern = /^[9][6-9]\d{8}$/;
if (!phonePattern.test(phone)) {
document.getElementById('phoneError').textContent = 'Please enter a valid Nepali phone number.';
isValid = false;
}
// Gender
const gender = document.getElementById('gender').value;
if (gender === '') {
document.getElementById('genderError').textContent = 'Gender is required.';
isValid = false;
}
if (isValid) {
document.getElementById('confirmationMessage').textContent = 'Form submitted successfully!';
}
return isValid;
}
</script>
</body>
</html>
3. User Login and Logout with Sessions
php
<!DOCTYPE html><html lang="en"><head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Login Form</title></head><body>
<form action="login.php" method="POST">
<label for="username">Username:</label>
<input type="text" id="username" name="username" required><br>
<label for="password">Password:</label>
<input type="password" id="password" name="password" required><br>
php
<?
phpsession_start();
$hardcoded_username = "admin";$hardcoded_password = "password123";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$username = $_POST['username'];
$password = $_POST['password'];
php
<?
phpsession_start();
if (!isset($_SESSION['loggedin']) || $_SESSION['loggedin'] !== true) {
header("Location: examples.php");
exit();}?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Dashboard</title></head><body>
<h1>Welcome,
<?php echo htmlspecialchars($_SESSION['username']); ?>!</h1>
<a href="logout.php">Logout</a>
</body>
</html>
php
<?
phpsession_start();session_unset();
session_destroy();?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Logged Out</title>
</head>
<body>
<p>You have been logged out.</p>
<a href="examples.php">Login Again</a>
</body>
</html>
o Date of Birth: Required field. The age should be between 18 and 99 years
old.
o Phone Number: Required field. Must be a valid Nepali phone number.
o Gender: Required field. Must select either "Male" or "Female".
o Ensure the form uses the POST method to submit data to phptest.php.
Server-Side Validation:
• In phptest.php, write PHP code to:
o Validate each input field.
o Display appropriate error messages if any validation fails.
o If all validations pass, display the submitted data back to the user.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Form Validation</title>
</head>
<body>
<form action="phptest.php" method="POST">
<label for="fullName">Full Name:</label>
<input type="text" id="fullName" name="fullName" required><br>
<label for="email">Email:</label>
<input type="email" id="email" name="email" required><br>
<label for="username">Username:</label>
<input type="text" id="username" name="username" required><br>
<label for="password">Password:</label>
<input type="password" id="password" name="password" required><br>
<label for="gender">Gender:</label>
<select id="gender" name="gender" required>
<option value="">Select</option>
<option value="Male">Male</option>
<option value="Female">Female</option>
</select><br>
write the PHP code for phptest.php to validate each input field and display appropriate error messages or the
submitted data:
<?php
function validate_date_of_birth($dob) {
$age = (new DateTime())->diff(new DateTime($dob))->y;
return ($age >= 18 && $age <= 99);
}
function validate_phone_number($phone) {
return preg_match('/^[9][6-9]\d{8}$/', $phone);
}
$errors = [];
$data = [];
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Full Name
if (empty($_POST["fullName"])) {
$errors["fullName"] = "Full Name is required.";
} else {
$data["fullName"] = $_POST["fullName"];
}
// Email
if (empty($_POST["email"]) || !filter_var($_POST["email"], FILTER_VALIDATE_EMAIL)) {
$errors["email"] = "Valid Email is required.";
} else {
$data["email"] = $_POST["email"];
}
// Username
if (empty($_POST["username"])) {
$errors["username"] = "Username is required.";
} else {
$data["username"] = $_POST["username"];
}
// Password
if (empty($_POST["password"]) || !preg_match('/^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{8,}$/',
$_POST["password"])) {
$errors["password"] = "Password must be at least 8 characters long and include at least one letter and
one number.";
}
// Confirm Password
if (empty($_POST["confirmPassword"]) || $_POST["confirmPassword"] !== $_POST["password"]) {
$errors["confirmPassword"] = "Passwords do not match.";
}
// Date of Birth
if (empty($_POST["dob"]) || !validate_date_of_birth($_POST["dob"])) {
$errors["dob"] = "Valid Date of Birth is required (Age 18-99).";
} else {
$data["dob"] = $_POST["dob"];
}
// Phone Number
if (empty($_POST["phone"]) || !validate_phone_number($_POST["phone"])) {
$errors["phone"] = "Valid Nepali Phone Number is required.";
} else {
$data["phone"] = $_POST["phone"];
}
// Gender
if (empty($_POST["gender"])) {
$errors["gender"] = "Gender is required.";
} else {
$data["gender"] = $_POST["gender"];
}
if (empty($errors)) {
echo "<h2>Submitted Data:</h2>";
foreach ($data as $key => $value) {
echo"<p>".htmlspecialchars(ucfirst($key)).": ".htmlspecialchars($value)."</p>";
}
} else {
echo "<h2>Errors:</h2>";
foreach ($errors as $error) {
echo "<p style='color:red;'>".htmlspecialchars($error)."</p>";
}
echo "<p><a href='examples.php'>Go back to the form</a></p>";
}
}
?>
php
<?phpclass Person {
public $name;
public $age;
public $gender;
// Destructor
public function __destruct() {
echo "Person object for {$this->name} is being destroyed.\n";
}}?>
php
<?phpclass Employee extends Person {
public $salary;
<?php
// Include the class definitions
include 'Person.php';
include 'Employee.php';
Person.php
php
<?phpclass Person {
public $name;
public $age;
public $gender;
// Destructor
public function __destruct() {
echo "Person object for {$this->name} is being destroyed.\n";
}}?>
Employee.php
php
<?phpinclude 'Person.php';
class Employee extends Person {
public $salary;
// Destructor
public function __destruct() {
echo "Employee object for {$this->name} is being destroyed.\n";
}}?>
php
<?phpinclude 'Employee.php';
// Create an instance of the Person class$person = new Person("John Doe", 30, "Male");echo $person->getDetails() . "\n";
// Create an instance of the Employee class$employee = new Employee("Jane Smith", 25, "Female", 50000);echo $employee-
>getDetails() . "\n";
// The destructors will automatically be called at the end of the script?>
Expected Output:
php
<?phptrait Logger {
public function log($message) {
echo "Log message: $message\n";
}}?>
php
<?phptrait Notifier {
public function sendNotification($message) {
echo "Notification: $message\n";
}}?>
php
<?phpclass User {
public function getUserDetails($name) {
echo "User's Name: $name\n";
}}?>
php
<?phpinclude 'Logger.php';include 'Notifier.php';include 'User.php';
class App extends User {
use Logger, Notifier;
// Destructor
public function __destruct() {
echo "App object is being destroyed.\n";
}}?>
php
<?phpinclude 'App.php';
// Create an instance of the App class$app = new App();$app->getUserDetails("John Doe");$app->log("This is a log message.");
$app->sendNotification("You have a new message!");
// The destructor will automatically be called at the end of the script
?>
7. Polymorphism in PHP
Instructions:
A. Create a Base Class: Animal
o Create a class Animal with a method sound() that outputs a generic message
like "Animal makes a sound."
php
<?phpclass Animal {
public function sound() {
echo "Animal makes a sound.\n";
}}?>
// Destructor
public function __destruct() {
echo "Dog object is being destroyed.\n";
}
}
// Destructor
public function __destruct() {
echo "Cat object is being destroyed.\n";
}
}
?>
C: Create a Function to Accept Animal Object
<?php
function makeSound(Animal $animal) {
$animal->sound();
}
?>
D: Interface Example
<?php
interface AnimalBehavior {
public function move();
}
// Destructor
public function __destruct() {
echo "Dog object is being destroyed.\n";
}
}
// Destructor
public function __destruct() {
echo "Cat object is being destroyed.\n";
}
}
?>
Demonstration Script (demo.php)
<?php
include 'Dog.php';
include 'Cat.php';
include 'makeSound.php';
Expected Output:
8. PHP and MySQL - Establishing Connection, Creating a Table, and Inserting Values
Task:
A. Establish Connection to MySQL Database:
Write a PHP script to connect to a MySQL database using the mysqli extension.
The connection should be established with a database student_db.
B. Create a Table:
After establishing the connection, write a query to create a table named students
with the following columns:
o id
o name
o age
C. Insert Values
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully\n";
?>
B: Create a Table
<?php
// SQL to create table
$sql = "CREATE TABLE IF NOT EXISTS students (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(30) NOT NULL,
age INT(3) NOT NULL
)";
// Close connection
$conn->close();
?>
Complete Script::
<?php
// Database credentials
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "student_db";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully\n";
// Close connection
$conn->close();
?>
B. Insert Values:
After creating the tables, insert the following records:
o In students table:
▪ Name: John Doe, Age: 25
▪ Name: Jane Smith, Age: 30
▪ Name: Alice Johnson, Age: 22
o In courses table:
▪ Course Name: PHP, Student ID: 1
▪ Course Name: MySQL, Student ID: 1
▪ Course Name: JavaScript, Student ID: 2
▪ Course Name: PHP, Student ID: 3
C. ORDER BY Query:
Write a query to fetch the details of all students from the students table, ordered
by their age in descending order.
D. GROUP BY Query:
Write a query to display the number of students enrolled in each course. Use the
GROUP BY clause to group by course_name in the courses table.
E. JOIN Query:
Write a query that performs an INNER JOIN between the students and courses
tables to display each student's name along with the courses they are enrolled in.
F. Display Results:
Display the results of each query in a structured format using echo in PHP. If no
results are found, display an appropriate message.
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
B: Insert Values
<?php
// Insert values into students table
$sql = "INSERT INTO students (name, age) VALUES
('John Doe', 25),
('Jane Smith', 30),
('Alice Johnson', 22)";
if ($conn->query($sql) === TRUE) {
echo "Values inserted into students table successfully\n";
} else {
echo "Error inserting values: " . $conn->error . "\n";
}
C: ORDER BY Query
<?php
// Query to fetch student details ordered by age in descending order
$sql = "SELECT * FROM students ORDER BY age DESC";
$result = $conn->query($sql);
E: JOIN Query
<?php
// Query to perform an INNER JOIN between students and courses
$sql = "SELECT students.name, courses.course_name FROM students INNER JOIN courses ON students.id
= courses.student_id";
$result = $conn->query($sql);
Complete Script
<?php
// Database credentials
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "student_db";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Create tables
$sql = "CREATE TABLE IF NOT EXISTS students (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(50) NOT NULL,
age INT(3) NOT NULL
)";
$conn->query($sql);
// ORDER BY query
$sql = "SELECT * FROM students ORDER BY age DESC";
$result = $conn->query($sql);
echo "Students ordered by age (desc):\n";
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "ID: " . $row["id"]. " - Name: " . $row["name"]. " - Age: " . $row["age"]. "\n";
}
} else {
echo "No students found\n";
}
// GROUP BY query
$sql = "SELECT course_name, COUNT(*) as student_count FROM courses GROUP BY course_name";
$result = $conn->query($sql);
echo "Number of students enrolled in each course:\n";
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "Course: " . $row["course_name"]. " - Students: " . $row["student_count"]. "\n";
}
} else {
echo "No courses found\n";
}
// JOIN query
$sql = "SELECT students.name, courses.course_name FROM students INNER JOIN courses ON students.id
= courses.student_id";
$result = $conn->query($sql);
echo "Students and their courses:\n";
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "Name: " . $row["name"]. " - Course: " . $row["course_name"]. "\n";
}
} else {
echo "No students enrolled in any courses\n";
}
// Close connection
$conn->close();
?>
10. jQuery
Task:
You are provided with a basic HTML file containing a paragraph, a list of items, a div, and
an image. Using jQuery, perform the following tasks:
A. Change the Paragraph Background Color:
Add a button that changes the background color of the paragraph to light blue
when clicked.
B. Hide the List of Items:
Implement a button that hides the list using a sliding animation.
C. Animate the Div Width:
Create a button that increases the width of the div from 300px to 500px over a
period of 1 second.
D. Highlight Even List Items:
Using jQuery, set the color of even-numbered list items to red.
E. Control Image Visibility:
Add three buttons to:
o Hide the image.
o Show the hidden image.
o Toggle between hiding and showing the image on each button press.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>jQuery Tasks</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<style>
#myDiv {
width: 300px;
height: 100px;
background-color: lightgray;
}
</style>
</head>
<body>
<p id="myParagraph">This is a paragraph.</p>
<button id="changeColorBtn">Change Paragraph Color</button>
<ul id="myList">
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
<li>Item 4</li>
</ul>
<button id="hideListBtn">Hide List</button>
<div id="myDiv"></div>
<button id="animateDivBtn">Animate Div Width</button>
<script>
$(document).ready(function() {
// Task A: Change Paragraph Background Color
$('#changeColorBtn').click(function() {
$('#myParagraph').css('background-color', 'lightblue');
});
$('#showImageBtn').click(function() {
$('#myImage').show();
});
$('#toggleImageBtn').click(function() {
$('#myImage').toggle();
});
});
</script>
</body>
</html>
11. AJAX
You are required to create a web page that accepts a user's name and age, and then allows
them to submit the data to the server using either the GET or POST method. On the
backend, implement a PHP script (fetch_data.php) that handles both GET and POST
requests, inserts the data into a MySQL database, and returns a confirmation message.
Tasks:
A. Create a MySQL database called user_db and a table named users. (columns:
id(pk), name, age)
B. Design a simple HTML form with the following fields:
• Name: Text field
• Age: Text field
• Two buttons:
o "Submit via GET": Triggers a GET request
o "Submit via POST": Triggers a POST request
C. Write JavaScript functions to send the form data to the server using AJAX. When
a user clicks on one of the buttons, the corresponding function should:
• Retrieve values from the input fields.
• Make an asynchronous request to the server using the chosen method (GET or
POST).
D. Implement a fetch_data.php script that:
• Establishes a connection to the MySQL database.
• Detects whether the request is GET or POST.
• Inserts the data into the users table and sends an appropriate response back.
E. Display the server’s response (confirmation message) in a <div> below the form
without reloading the page.
USE user_db;
<label for="age">Age:</label>
<input type="text" id="age" name="age" required><br>
<div id="responseMessage"></div>
<script>
function submitForm(method) {
let name = $('#name').val();
let age = $('#age').val();
let url = 'fetch_data.php';
$.ajax({
url: url,
type: method,
data: {
name: name,
age: age
},
success: function(response) {
$('#responseMessage').html(response);
},
error: function() {
$('#responseMessage').html('An error occurred');
}
});
}
</script>
</body>
</html>
D: Implement fetch_data.php Script
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "user_db";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Close connection
$conn->close();
?>
E: Display the Server’s Response