0% found this document useful (0 votes)
19 views

Simple Lab

The document contains examples of JavaScript code to validate form fields, evaluate mathematical expressions, add dynamic effects with layers and animation, calculate sums of natural numbers, display the current date in words, calculate student exam results including total, average, grade, and calculate employee payroll details.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views

Simple Lab

The document contains examples of JavaScript code to validate form fields, evaluate mathematical expressions, add dynamic effects with layers and animation, calculate sums of natural numbers, display the current date in words, calculate student exam results including total, average, grade, and calculate employee payroll details.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 19

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>

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>

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>
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>
5. .Write a JavaScript code block using arrays and generate the current date in words, this should include
the day, month and year.

<html>

<body>
<script>
// 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 in console result


console.log("Current Date in Words:", currentDateInWords);

//Display the result in html page


document.write("Current Date in Words:", currentDateInWords);

</script>
</body>
</html>

6. .Create a form for Student information. Write JavaScript code to find Total, Average, Result and
Grade.

<!DOCTYPE html>
<html lang="en">
<head>

<title>Student Results</title>
<script>
function calculateResults() {
var marks = document.getElementsByClassName('marks');
var total = 0;

for (var i = 0; i < marks.length; i++) {


total += parseInt(marks[i].value, 10);
}

var average = total / marks.length;

var result = average >= 40 ? "Pass" : "Fail";

var grade = '';

if (average >= 80) {


grade = 'A';
}
else if (average >= 60) {
grade = 'B';
}
else if (average >= 40) {
grade = 'C';
}
else {
grade = 'F';
}

document.getElementById('total').innerHTML = 'Total: ' + total;


document.getElementById('average').innerHTML = 'Average: ' +
average.toFixed(2);
document.getElementById('result').innerHTML = 'Result: ' + result;
document.getElementById('grade').innerHTML = 'Grade: ' + grade;
}
</script>
</head>
<body>
<h2>Student Information</h2>
<form>
Name: <input type="text">
<br><br>
Marks 1: <input type="number" class="marks"><br><br>
Marks 2: <input type="number" class="marks"><br><br>
Marks 3: <input type="number" class="marks"><br><br>
<button type="button" onclick="calculateResults()">Calculate</button>
</form>

<p id="total"></p>
<p id="average"></p>
<p id="result"></p>
<p id="grade"></p>
</body>
</html>

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 lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Employee Payroll Calculation</title>
</head>
<body>

<h1>Employee Information Form</h1>

<form id="employeeForm">
<label for="basicPay">Basic Pay: </label><input type="number"
id="basicPayInput">
<button type="button" onclick="calculatePay()">Calculate</button>
</form>

<h2>Payroll Details</h2>
<p id="result"></p>

<script>
function calculatePay() {
const basicPay =
parseFloat(document.getElementById('basicPayInput').value);

// Constants for percentages (can be adjusted)


const DA_PERCENT = 20; // 20% of Basic Pay
const HRA_PERCENT = 15; // 15% of Basic Pay
const PF_PERCENT = 12; // 12% of Basic Pay
const TAX_PERCENT = 10; // 10% of Gross Pay

// Calculations
const DA = basicPay * (DA_PERCENT / 100);
const HRA = basicPay * (HRA_PERCENT / 100);
const PF = basicPay * (PF_PERCENT / 100);

const grossPay = basicPay + DA + HRA;


const tax = grossPay * (TAX_PERCENT / 100);
const deductions = PF + tax;
const netPay = grossPay - deductions;

// Displaying the results


const resultDiv = document.getElementById('result');
resultDiv.innerHTML = `
<strong>Basic Pay:</strong> ${basicPay.toFixed(2)}<br>
<strong>DA:</strong> ${DA.toFixed(2)}<br>
<strong>HRA:</strong> ${HRA.toFixed(2)}<br>
<strong>PF:</strong> ${PF.toFixed(2)}<br>
<strong>Gross Pay:</strong> ${grossPay.toFixed(2)}<br>
<strong>Tax:</strong> ${tax.toFixed(2)}<br>
<strong>Deductions:</strong> ${deductions.toFixed(2)}<br>
<strong>Net Pay:</strong> ${netPay.toFixed(2)}<br>
`;
}
</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
// Get the current day of the week as a number (0 for Sunday, 6 for Saturday)
$dayOfWeek = date("w");

// Array to store background colors for each day of the week


$backgroundColors = array(
"orange", // Sunday
"pink", // Monday
"yellow", // Tuesday
"black", // Wednesday
"red", // Thursday
"green", // Friday
"white" // Saturday
);

// Set the background color based on the current day


if ($dayOfWeek >= 0 && $dayOfWeek <= 6) {
$backgroundColor = $backgroundColors[$dayOfWeek];
} else {
$backgroundColor = "#f2f2f2"; // Default background color
}
?>

<h1>Background Color of the Day</h1>

<div style="background-color: <?php echo $backgroundColor; ?>">


Today is <?php echo date("l"); ?>
</div>
</body>
</html>

9.Write a simple program in PHP for i) generating Prime number ii) generate Fibonacci series.

<?php
function generatePrimes($maxNumber) {
echo "Prime numbers up to $maxNumber: ";

for ($number = 2; $number <= $maxNumber; $number++) {


$isPrime = true;

for ($i = 2; $i <= sqrt($number); $i++) {


if ($number % $i == 0) {
$isPrime = false;
break;
}
}

if ($isPrime) {
echo $number . " ";
}
}

echo "<br>";
}

function fibonacciSeries($numTerms) {
$first = 0;
$second = 1;

echo "Fibonacci Series ($numTerms terms): ";


for ($i = 0; $i < $numTerms; $i++) {
echo $first . " ";

$next = $first + $second;


$first = $second;
$second = $next;
}

echo "<br>";
}

// Call the functions with desired parameters


generatePrimes(58); // Generate prime numbers up to 58
fibonacciSeries(10); // Generate 10 terms of the Fibonacci series
?>
10. Write a PHP program to remove duplicates from a sorted list.

<?php
function removeDuplicates($array) {
$uniqueList = array_unique($array);

echo "Original List: ";


print_r($array);

echo "<br>Unique List: ";


print_r($uniqueList);
}

$sortedList = [1, 1, 2, 2, 3, 3, 4, 5, 5]; // Example sorted list


removeDuplicates($sortedList);
?>

11.Write a PHP Script to print the following pattern on the Screen:

<?php
for ($i = 5; $i >= 1; $i--) {
for ($j = 5; $j > $i; $j--) {
echo "&nbsp";
}
for($k=1;$k<=$i;$k++)
{
echo "*";
}
echo "<br>";
}
?>

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' => 'guru@example.com', 'age' => 23],
['name' => 'Prajwal', 'email' => 'prajwal@example.com', 'age' => 25],
['name' => 'virat', 'email' => 'virat@example.com', '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>

13. Write a function in PHP to generate captcha code.

<?php

session_start();

function generateCaptchaCode($length = 6) {
$characters =
'0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$charactersLength = strlen($characters);
$captchaCode = '';

for ($i = 0; $i < $length; $i++) {


$captchaCode .= $characters[rand(0, $charactersLength - 1)];
}

return $captchaCode;
}

$captchaCode = generateCaptchaCode();
echo "Captcha Code is: " . $captchaCode;

// You can store $captchaCode in the session or use it as needed in your


application.

?>
14 Write a program in PHP to read and write file using form control

First create html program inside htdocs folder with the .html extension

<!DOCTYPE html>
<html>

<head>
<title>File Reader and Writer</title>
</head>

<body>
<form action="read.php" method="post">
<label for="textdata">Enter Text: </label><br>
<textarea name="textdata" id="textdata"></textarea><br>
<input type="submit" value="Write to File"><br><br>
</form>

<form action="read.php" method="post" enctype="multipart/form-data">


<label for="filedata">Upload File to Read File Contents: </label>
<input type="file" name="filedata" id="filedata">
<input type="submit" value="Read File Contents"><br><br>
</form>

</body>

</html>

Second you have to create one php program with .php extension

<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (!empty($_POST['textdata'])) {
file_put_contents("output.txt", $_POST['textdata']);
echo "Data written to file.<br>";
}

if (!empty($_FILES['filedata']['tmp_name'])) {
$fileContent = file_get_contents($_FILES['filedata']['tmp_name']);
echo "File content: " . htmlspecialchars($fileContent) . "<br>";
}
}
?>

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>
&copy; <?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>

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy