1.
Create a form with the elements of Textboxes, Radio buttons, Checkboxes, and so
on. Write JavaScript code to validate the format in email, and mobile number in 10
characters, If a textbox has been left empty, popup an alert indicating when email,
mobile number and textbox has been left empty.
<!DOCTYPE html>
<html>
<head>
<title>Form Validation</title>
</head>
<body>
<h3 style="text-align:center">Validation Form</h3>
<form id="myForm" style="WIDTH:25%; MARGIN:0 AUTO;border:solid
orange;margintop:3%; padding:20px">
<label>Name:</label>
<input type="text" id="name" required><br><br>
<label>Email:</label>
<input type="text" id="email"><br><br>
<label>Mobile No:</label>
<input type="text" id="mobile"><br><br>
<label>Gender:</label>
<input type="radio" name="gender" value="male">Male
<input type="radio" name="gender" value="female">Female<br><br>
<label>Hobbies:</label>
<input type="checkbox" name="hobby" value="reading">Reading
<input type="checkbox" name="hobby" value="gaming">Gaming
<input type="checkbox" name="hobby" value="traveling">Traveling<br><br>
<input type="button" value="Submit" onclick="validateForm()">
</form>
<script>
function validateForm() {
var name = document.getElementById("name").value;
var email = document.getElementById("email").value;
var mobile = document.getElementById("mobile").value;
if (name === "" || email === "" || mobile === "") {
alert("Please fill in all required fields.");
return;
}
var emailPattern = "[a-zA-Z0-9]+@[a-zA-Z]+.[a-z]{2,3}";
var mobilePattern = "^[7-9]{1}[0-9]{9}$";
if (!email.match(emailPattern)) {
alert("Invalid email format.");
return;
}
if (!mobile.match(mobilePattern)) {
alert("Mobile number must be 10 digits.");
return;
}
}
</script>
</body>
</html>
</html>
Output
.2. Develop an HTML Form, which accepts any Mathematical expression. Write
JavaScript code to Evaluate the expression and Display the result.
<!DOCTYPE html>
<html>
<head>
<title>Math Expression Evaluator</title>
</head>
<body>
<h1>Math Expression Evaluator</h1>
<form id="calculator-form">
<input type="text" id="expression" placeholder="Enter a mathematical expression"
required>
<button type="button" onclick="calculate()">Calculate</button>
</form>
<p>Result: <span id="result">---</span></p>
<script>
function calculate()
{
const expression = document.getElementById("expression").value;
try {
const result = eval(expression);
document.getElementById("result").textContent = result;
}
catch (error)
{
document.getElementById("result").textContent = "Error";
}
}
</script>
</body>
</html>
output
3. Create a page with dynamic effects. Write the code to include layers and
basic animation.
<!DOCTYPE html>
<html>
<head>
<title>Dynamic Effects and Animations</title>
<style>
.layer {
position: absolute;
width: 100px;
height: 100px;
background-color: pink;
border: 2px solid red;
border-radius: 50%;
transition: transform 0.5s ease;
}
</style>
</head>
<body>
<h1>Dynamic Effects and Animations</h1>
<!-- Layers with basic animations -->
<div class="layer" id="layer1" onmouseover="moveLayer(this)"></div>
<div class="layer" id="layer2" onmouseover="moveLayer(this)"></div>
<div class="layer" id="layer3" onmouseover="moveLayer(this)"></div>
<script>
// Function to move and animate a layer
function moveLayer(layer) {
const maxX = window.innerWidth - 120; // Max X position
const maxY = window.innerHeight - 120; // Max Y position
// Generate random X and Y positions within the window
const randomX = Math.floor(Math.random() * maxX);
const randomY = Math.floor(Math.random() * maxY);
// Move the layer to the random position
layer.style.transform = `translate(${randomX}px, ${randomY}px)`;
}
</script>
</body>
</html>
Output
4.write a JavaScript code to find the sum of N natural Numbers. (Use user
defined function)
<!DOCTYPE html>
<html>
<head>
<title>Sum of N Natural Numbers</title>
</head>
<body>
<h1>Sum of N Natural Numbers</h1>
<form>
<label for="n">Enter a positive integer (N): </label>
<input type="number" id="n">
<button type="button" onclick="calculateSum()">Calculate Sum</button>
</form>
<p id="result">The sum of the first N natural numbers is: <span id="sum">---</span></p>
<script>
function calculateSum() {
const n = parseInt(document.getElementById("n").value);
if (n >= 1) {
const sum = sumOfNaturalNumbers(n);
document.getElementById("sum").textContent = sum;
}
else {
document.getElementById("sum").textContent = "Please enter a positive integer (N >=
1).";
}
}
function sumOfNaturalNumbers(n) {
return (n * (n + 1)) / 2;
}
</script>
</body>
</html>
Output
5.Write a JavaScript code block using arrays and generate the current date in
words, this should include the day, month and year.
// Arrays to store the names of days and months
const daysOfWeek = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday",
"Friday", "Saturday"];
const monthsOfYear = ["January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"];
// Get the current date
const currentDate = new Date();
// Extract day, month, and year components
const currentDay = daysOfWeek[currentDate.getDay()];
const currentMonth = monthsOfYear[currentDate.getMonth()];
const currentYear = currentDate.getFullYear();
// Create a sentence with the current date in words
const currentDateInWords = `${currentDay}, ${currentMonth} $
{currentDate.getDate()}, ${currentYear}`;
// Display the result
console.log("Current Date in Words:", currentDateInWords);
output
Current Date in Words: Sunday, October 22, 2023
6.Create a form for Student information. Write JavaScript code to find Total,
Average, Result and Grade.
<!DOCTYPE html>
<html>
<head>
<title>Student Information</title>
</head>
<body>
<h1>Student Information Form</h1>
<form id="student-form">
<label for="name">Student Name:</label>
<input type="text" id="name" required><br>
<label for="math">Math Score:</label>
<input type="number" id="math" required><br>
<label for="science">Science Score:</label>
<input type="number" id="science" required><br>
<label for="history">History Score:</label>
<input type="number" id="history" required><br>
<button type="button" onclick="calculateResult()">Calculate</button><br>
<label for="total">Total Score:</label>
<input type="text" id="total" readonly><br>
<label for="average">Average Score:</label>
<input type="text" id="average" readonly><br>
<label for="result">Result:</label>
<input type="text" id="result" readonly><br>
<label for="grade">Grade:</label>
<input type="text" id="grade" readonly>
</form>
<script>
function calculateResult() {
const mathScore = parseInt(document.getElementById("math").value);
const scienceScore = parseInt(document.getElementById("science").value);
const historyScore = parseInt(document.getElementById("history").value);
const totalScore = mathScore + scienceScore + historyScore;
const averageScore = totalScore / 3;
document.getElementById("total").value = totalScore;
document.getElementById("average").value = averageScore;
if (mathScore >= 40 && scienceScore >= 40 && historyScore >= 40)
{
document.getElementById("result").value = "Pass";
if (averageScore >= 70)
{
document.getElementById("grade").value = "A";
}
else if (averageScore >= 60) {
document.getElementById("grade").value = "B";
}
else if (averageScore >= 50)
{
document.getElementById("grade").value = "C";
}
else {
document.getElementById("grade").value = "D";
}
}
else {
document.getElementById("result").value = "Fail";
document.getElementById("grade").value = "F";
}
}
</script>
</body>
</html>
Output
7. Create a form for Employee information. Write JavaScript code to find DA, HRA, PF,
TAX, Gross pay, Deduction and Net pay.
<!DOCTYPE html>
<html>
<head>
<title>Employee Information</title>
</head>
<body>
<h1>Employee Information Form</h1>
<form id="employee-form">
<label for="name">Employee Name:</label>
<input type="text" id="name" required><br>
<label for="basic">Basic Salary:</label>
<input type="number" id="basic" required><br>
<label for="daPercentage">DA Percentage (%):</label>
<input type="number" id="daPercentage" required><br>
<label for="hraPercentage">HRA Percentage (%):</label>
<input type="number" id="hraPercentage" required><br>
<label for="pfPercentage">PF Percentage (%):</label>
<input type="number" id="pfPercentage" required><br>
<label for="taxPercentage">Income Tax Percentage (%):</label>
<input type="number" id="taxPercentage" required><br>
<button type="button" onclick="calculateSalary()">Calculate</button><br>
<label for="da">Dearness Allowance (DA):</label>
<input type="text" id="da" readonly><br>
<label for="hra">House Rent Allowance (HRA):</label>
<input type="text" id="hra" readonly><br>
<label for="pf">Provident Fund (PF):</label>
<input type="text" id="pf" readonly><br>
<label for="tax">Income Tax (TAX):</label>
<input type="text" id="tax" readonly><br>
<label for="grossPay">Gross Pay:</label>
<input type="text" id="grossPay" readonly><br>
<label for="deduction">Deduction:</label>
<input type="text" id="deduction" readonly><br>
<label for="netPay">Net Pay:</label>
<input type="text" id="netPay" readonly>
</form>
<script>
function calculateSalary() {
const basicSalary = parseFloat(document.getElementById("basic").value);
const daPercentage = parseFloat(document.getElementById("daPercentage").value);
const hraPercentage = parseFloat(document.getElementById("hraPercentage").value);
const pfPercentage = parseFloat(document.getElementById("pfPercentage").value);
const taxPercentage = parseFloat(document.getElementById("taxPercentage").value);
// Calculate DA, HRA, PF, TAX
const da = (daPercentage / 100) * basicSalary;
const hra = (hraPercentage / 100) * basicSalary;
const pf = (pfPercentage / 100) * basicSalary;
const tax = (taxPercentage / 100) * basicSalary;
// Calculate Gross Pay and Deduction
const grossPay = basicSalary + da + hra;
const deduction = pf + tax;
// Calculate Net Pay
const netPay = grossPay - deduction;
document.getElementById("da").value = da.toFixed(2);
document.getElementById("hra").value = hra.toFixed(2);
document.getElementById("pf").value = pf.toFixed(2);
document.getElementById("tax").value = tax.toFixed(2);
document.getElementById("grossPay").value = grossPay.toFixed(2);
document.getElementById("deduction").value = deduction.toFixed(2);
document.getElementById("netPay").value = netPay.toFixed(2);
}
</script>
</body>
</html>
8.Write a program in PHP to change background color based on day of the week using if
else if statements and using arrays .
<!DOCTYPE html>
<html>
<head>
<title>Change Background Color by Day of the Week</title>
<style>
body {
text-align: center;
font-size: 24px;
padding: 50px;
}
</style>
</head>
<body>
<?php
// Array to store background colors for each day of the week
$backgroundColors = array(
"Sunday" => "#ff6666",
"Monday" => "#ffcc99",
"Tuesday" => "#99ff99",
"Wednesday" => "#66b3ff",
"Thursday" => "#ff99cc",
"Friday" => "#ffff99",
"Saturday" => "#cc99ff"
);
// Get the current day of the week
$currentDay = date("l");
// Set the background color based on the current day
if (array_key_exists($currentDay, $backgroundColors)) {
$backgroundColor = $backgroundColors[$currentDay];
} else {
$backgroundColor = "#f2f2f2"; // Default background color
}
?>
<h1>Background Color of the Day</h1>
<div style="background-color: <?php echo $backgroundColor; ?>">
Today is <?php echo $currentDay; ?>
</div>
</body>
</html>
Output
9.Write a simple program in PHP for i) generating Prime number ii) generate Fibonacci
series.
<?php
function isPrime($number) {
if ($number <= 1) {
return false;
}
if ($number <= 3) {
return true;
}
if ($number % 2 == 0 || $number % 3 == 0) {
return false;
}
for ($i = 5; $i * $i <= $number; $i += 6) {
if ($number % $i == 0 || $number % ($i + 2) == 0) {
return false;
}
}
return true;
}
echo "Prime Numbers: ";
for ($i = 2; $i <= 50; $i++) {
if (isPrime($i)) {
echo $i . " ";
}
}
echo "\nFibonacci Series: ";
$n = 10; // Number of Fibonacci numbers to generate
$a = 0;
$b = 1;
for ($i = 0; $i < $n; $i++) {
echo $a . " ";
$c = $a + $b;
$a = $b;
$b = $c;
}
?>
output
10.Write a PHP program to remove duplicates from a sorted list.
<?php
function removeDuplicates($sortedList) {
$length = count($sortedList);
if ($length == 0) {
return $sortedList;
}
$result = array($sortedList[0]);
for ($i = 1; $i < $length; $i++) {
if ($sortedList[$i] != $sortedList[$i - 1]) {
$result[] = $sortedList[$i];
}
}
return $result;
}
// Sample sorted list with duplicates
$sortedList = array(1, 2, 2, 3, 4, 4, 4, 5, 6, 6, 7);
// Call the removeDuplicates function
$uniqueList = removeDuplicates($sortedList);
echo "Original Sorted List: " . implode(", ", $sortedList) . "\n";
echo "List with Duplicates Removed: " . implode(", ", $uniqueList) . "\n";
?>
output
Original Sorted List: 1, 2, 2, 3, 4, 4, 4, 5, 6, 6, 7 List with Duplicates Removed: 1, 2, 3, 4, 5, 6,
11. Write a PHP Script to print the following pattern on the Screen:
<?php
$rows = 5; // Number of rows in the pattern
<?php
//$rows = 5; // Number of rows in the pattern
for ($i = 1; $i <= 5; $i++) {
for ($j = 5; $j >= $i; $j--) {
echo "*";
}
echo "\n";
}
?>
Output
*****
****
***
**
*
12. Write a simple program in PHP for Searching of data by different criteria.
<!DOCTYPE html>
<html>
<head>
<title>Search Data</title>
</head>
<body>
<h2>Search Data</h2>
<form method="post" action="">
<label>Name:</label>
<input type="text" name="name">
<br><br>
<label>Email:</label>
<input type="text" name="email">
<br><br>
<label>Age:</label>
<input type="text" name="age">
<br><br>
<input type="submit" name="search" value="Search">
</form>
<?php
// Sample data array
$data = [
['name' => 'Guru', 'email' => '[email protected]', 'age' => 23],
['name' => 'Prajwal', 'email' => '[email protected]', 'age' => 25],
['name' => 'virat', 'email' => '[email protected]', 'age' => 35],
];
if (isset($_POST['search'])) {
$searchName = $_POST['name'];
$searchEmail = $_POST['email'];
$searchAge = $_POST['age'];
// Perform the search
$results = [];
foreach ($data as $item) {
if (
(empty($searchName) || stripos($item['name'], $searchName) !== false) &&
(empty($searchEmail) || stripos($item['email'], $searchEmail) !== false) &&
(empty($searchAge) || $item['age'] == $searchAge)
){
$results[] = $item;
}
}
// Display the results
if (!empty($results)) {
echo "<h3>Search Results:</h3>";
echo "<ul>";
foreach ($results as $result) {
echo "<li>Name: {$result['name']}, Email: {$result['email']}, Age:
{$result['age']}</li>";
}
echo "</ul>";
} else {
echo "No results found.";
}
}
?>
</body>
</html>
output
13. Write a function in PHP to generate captcha code.
<?php
// Function to generate a random CAPTCHA code
function generateCaptchaCode($length = 6) {
$characters =
'0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$captchaCode = '';
for ($i = 0; $i < $length; $i++) {
$randomIndex = rand(0, strlen($characters) - 1);
$captchaCode .= $characters[$randomIndex];
}
return $captchaCode;
}
// Generate a CAPTCHA code and store it in a session variable
session_start();
$captchaCode = generateCaptchaCode();
$_SESSION['captcha_code'] = $captchaCode;
// Create an image with the CAPTCHA code and display it to the user
$width = 150;
$height = 50;
$image = imagecreatetruecolor($width, $height);
$bgColor = imagecolorallocate($image, 255, 255, 255);
$textColor = imagecolorallocate($image, 0, 0, 0);
imagefilledrectangle($image, 0, 0, $width, $height, $bgColor);
// You can choose a font file for your CAPTCHA text
$font = 'path_to_your_font.ttf';
imagettftext($image, 20, 0, 10, 30, $textColor, $font, $captchaCode);
header('Content-type: image/png');
imagepng($image);
imagedestroy($image);
?>
14. Write a program in PHP to read and write file using form control.
<!DOCTYPE html>
<html>
<head>
<title>File Upload and Read</title>
</head>
<body>
<h2>Upload a File</h2>
<form method="post" action="" enctype="multipart/form-data">
<input type="file" name="file" id="file">
<input type="submit" name="upload" value="Upload">
</form>
<h2>Read Uploaded File</h2>
<form method="get" action="">
<label>File Name:</label>
<input type="text" name="filename">
<input type="submit" value="Read">
</form>
<?php
if (isset($_POST['upload'])) {
if ($_FILES['file']['error'] === UPLOAD_ERR_OK) {
$tempFile = $_FILES['file']['tmp_name'];
$uploadDir = 'uploads/';
$targetFile = $uploadDir . $_FILES['file']['name'];
if (!file_exists($uploadDir)) {
mkdir($uploadDir, 0777, true);
}
if (move_uploaded_file($tempFile, $targetFile)) {
echo "File uploaded successfully.";
} else {
echo "Error uploading the file.";
}
}
}
if (isset($_GET['filename'])) {
$filename = 'uploads/' . $_GET['filename'];
if (file_exists($filename)) {
$fileContents = file_get_contents($filename);
echo "<h3>File Contents:</h3>";
echo "<pre>" . htmlspecialchars($fileContents) . "</pre>";
} else {
echo "File not found.";
}
}
?>
</body>
</html>
Write a program in PHP to add, update and delete using student database.
15. Write a PHP program to Create a simple webpage of a college.
<!DOCTYPE html>
<html>
<head>
<title>College Name - Home</title>
<style>
body {
font-family: Arial, sans-serif;
}
header {
background-color: #007ACC;
color: #fff;
text-align: center;
padding: 20px;
}
h1 {
margin: 0;
}
nav {
background-color: #333;
color: #fff;
padding: 10px;
}
nav a {
color: #fff;
text-decoration: none;
margin-right: 20px;
}
.content {
padding: 20px;
}
footer {
background-color: #333;
color: #fff;
text-align: center;
padding: 10px;
}
</style>
</head>
<body>
<header>
<h1>College Name</h1>
<p>Empowering the Future</p>
</header>
<nav>
<a href="#">Home</a>
<a href="#">Programs</a>
<a href="#">Admissions</a>
<a href="#">About Us</a>
<a href="#">Contact Us</a>
</nav>
<div class="content">
<h2>Welcome to College Name</h2>
<p>
Welcome to College Name, where we are committed to providing a quality education
and empowering the future.
</p>
</div>
<footer>
© <?php echo date("Y"); ?> College Name
</footer>
</body>
</html>
16. Write a program in PHP for exception handling for i) divide by zero ii) checking date
format.
<!DOCTYPE html>
<html>
<head>
<title>Exception Handling</title>
</head>
<body>
<h2>Exception Handling</h2>
<form method="post" action="">
<label>Divide a Number by:</label>
<input type="text" name="divider" placeholder="Enter a number">
<input type="submit" name="divide" value="Divide">
<br><br>
<label>Check Date Format:</label>
<input type="text" name="date" placeholder="YYYY-MM-DD">
<input type="submit" name="check_date" value="Check Date Format">
</form>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
try {
if (isset($_POST["divide"])) {
$divider = (int)$_POST["divider"];
if ($divider === 0) {
throw new Exception("Cannot divide by zero.");
}
$result = 10 / $divider;
echo "Result of 10 divided by $divider is $result.";
}
if (isset($_POST["check_date"])) {
$date = $_POST["date"];
if (!preg_match("/^\d{4}-\d{2}-\d{2}$/", $date) || !checkdate(substr($date, 5,
2), substr($date, 8, 2), substr($date, 0, 4))) {
throw new Exception("Invalid date format. Use YYYY-MM-DD format.");
}
echo "Date format is valid: $date";
}
} catch (Exception $e) {
echo "Error: " . $e->getMessage();
}
}
?>
</body>
</html>
output
17.Write a program in PHP to Validate Input
<!DOCTYPE html>
<html>
<head>
<title>Input Validation</title>
</head>
<body>
<h1>Input Validation</h1>
<form method="post">
<label for="name">Name:</label>
<input type="text" name="name" id="name" required><br><br>
<label for="email">Email:</label>
<input type="text" name="email" id="email" required><br><br>
<label for="password">Password:</label>
<input type="password" name="password" id="password" required><br><br>
<button type="submit" name="submit">Submit</button>
</form>
<?php
if (isset($_POST['submit'])) {
$name = $_POST['name'];
$email = $_POST['email'];
$password = $_POST['password'];
// Validate name (letters and spaces only)
if (!preg_match('/^[a-zA-Z\s]+$/', $name)) {
echo "Invalid name. Please enter a valid name containing only letters and
spaces.<br>";
}
// Validate email format
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo "Invalid email address. Please enter a valid email.<br>";
}
// Validate password criteria (e.g., at least 8 characters)
if (strlen($password) < 8) {
echo "Invalid password. It must be at least 8 characters long.<br>";
}
if (preg_match('/^[a-zA-Z\s]+$/', $name) && filter_var($email,
FILTER_VALIDATE_EMAIL) && strlen($password) >= 8) {
echo "Valid input: Name - $name, Email - $email, Password - $password";
}
}
?>
</body>
</html>
output
18.Write a program in PHP for setting and retrieving a cookie.
<!DOCTYPE html>
<html>
<head>
<title>Cookie Example</title>
</head>
<body>
<h1>Cookie Example</h1>
<?php
// Check if the cookie has been set and display its value
if (isset($_COOKIE['user'])) {
$username = $_COOKIE['user'];
echo "Welcome back, $username! Your cookie value is: $username";
} else {
echo "No cookie set. Please enter your username to set a cookie.";
}
// If the form is submitted, set a cookie
if (isset($_POST['submit'])) {
$username = $_POST['username'];
// Set a cookie with a name "user" and the provided username as the value
setcookie('user', $username, time() + 3600, '/'); // Cookie expires in 1 hour
// Display a message
echo "Cookie set! Welcome, $username!";
}
?>
<form method="post">
<label for="username">Enter your username:</label>
<input type="text" name="username" id="username" required>
<button type="submit" name="submit">Set Cookie</button>
</form>
</body>
</html>