0% found this document useful (0 votes)
15 views15 pages

WP 10 prgm-2

Uploaded by

ruthlessfake73
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)
15 views15 pages

WP 10 prgm-2

Uploaded by

ruthlessfake73
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/ 15

Program 01

<!DOCTYPE html>
<html>
<head>
<title>Form Validation</title>
<script>
function validateForm() {
const email = document.getElementById('email').value;
const mobile = document.getElementById('mobile').value;
const textbox = document.getElementById('textbox').value;
let errorMessage = "";

// Validate email format


if (!validateEmail(email)) {
errorMessage += "Invalid email format.\n";
}

// Validate mobile number length


if (mobile.length !== 10) {
errorMessage += "Mobile number should be 10 characters.\n";
}

// Check if any field is left empty


if (email === "" || mobile === "" || textbox === "") {
errorMessage += "Please fill in all fields.\n";
}

// Display error message in an alert if any validation fails


if (errorMessage !== "") {
alert(errorMessage);
return false; // Prevent form submission
}

return true; // Allow form submission


}

// Function to validate email format using a regular expression


function validateEmail(email) {
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
return emailRegex.test(email);
}
</script>
</head>
<body>
<h2>Form Validation</h2>
<form onsubmit="return validateForm()">
Email: <input type="text" id="email"><br><br>
Mobile Number: <input type="text" id="mobile"><br><br>
Textbox: <input type="text" id="textbox"><br><br>
Gender:
<input type="radio" id="male" name="gender" value="male">
<label for="male">Male</label>
<input type="radio" id="female" name="gender" value="female"> <label
for="female">Female</label><br><br>
Interests:
<input type="checkbox" id="music" name="interest" value="music">
<label for="music">Music</label>
<input type="checkbox" id="sports" name="interest" value="sports"> <label
for="sports">Sports</label><br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>

Program 02

<!DOCTYPE html>
<html>
<head>
<title>Math Expression Evaluator</title>
<script>
function evaluateExpression() {
const expression = document.getElementById('expression').value;

try {
const result = eval(expression);
document.getElementById('result').textContent = `Result: ${result}`;
} catch (error) {
document.getElementById('result').textContent = "Invalid expression or operation.";
}
}
</script>
</head>
<body>
<h2>Math Expression Evaluator</h2>

<form>
Enter a mathematical expression:
<input type="text" id="expression">
<input type="button" value="Evaluate" onclick="evaluateExpression()">
</form>

<p id="result"></p>

</body>
</html>

Program 03

<!DOCTYPE html>
<html>
<head>
<title>Dynamic Effects with Layers and Basic Animation</title>
<style>
.layer {
position: absolute;
width: 100px;
height: 100px;
background-color: #3498db;
border-radius: 50%;
transition: all 0.5s ease-in-out;
}
</style>
</head>
<body>

<div class="layer" id="layer1"></div>


<div class="layer" id="layer2"></div>
<div class="layer" id="layer3"></div>

<script>
function moveLayers() {
const layer1 = document.getElementById('layer1');
const layer2 = document.getElementById('layer2');
const layer3 = document.getElementById('layer3');

// Change the position of layers using JavaScript


layer1.style.transform = "translate(150px, 150px)";
layer2.style.transform = "translate(300px, 300px)";
layer3.style.transform = "translate(450px, 450px)";
}

// Call the moveLayers function after a 1-second delay


setTimeout(moveLayers, 1000);
</script>

</body>
</html>

Program 04

<!DOCTYPE html>
<html>
<head>
<title>Sum of N Natural Numbers</title>
<script>
function sumOfNaturalNumbers(n) {
let sum = 0;
for (let i = 1; i <= n; i++) {
sum += i;
}
return sum; // Return sum after the loop completes
}

function calculateSum() {
const N = parseInt(document.getElementById('number').value);
if (!isNaN(N) && N > 0) {
const sum = sumOfNaturalNumbers(N);
document.getElementById('result').textContent = `The sum of first ${N} natural numbers is:
${sum}`;
} else {
document.getElementById('result').textContent = "Please enter a valid positive integer.";
}
}
</script>
</head>
<body>
<h2>Sum of N Natural Numbers</h2>
Enter a positive integer (N): <input type="text" id="number">
<button onclick="calculateSum()">Calculate</button>
<p id="result"></p>
</body>
</html>

Program 05

<!DOCTYPE html>
<html>
<head>
<title>Current Date in Words</title>
</head>
<body>

<h2>Current Date in Words</h2>


<p id="dateInWords"></p>

<script>
const daysOfWeek = [
"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"
];

const monthsOfYear = [
"January", "February", "March", "April", "May", "June", "July", "August", "September",
"October", "November", "December"
];

const currentDate = new Date();


const day = daysOfWeek[currentDate.getDay()];
const month = monthsOfYear[currentDate.getMonth()];
const year = currentDate.getFullYear();

const currentDateInWords = `${day}, ${month} ${currentDate.getDate()}, ${year}`;


document.getElementById('dateInWords').textContent = "Current date in words: " +
currentDateInWords;
</script>

</body>
</html>

Program 06

<!DOCTYPE html>
<html>
<head>
<title>Student Information Form</title>
<script>
function calculateResult() {
var math = parseFloat(document.getElementById('math').value);
var science = parseFloat(document.getElementById('science').value);
var english = parseFloat(document.getElementById('english').value);

var totalMarks = math + science + english;


var average = totalMarks / 3;

var result = (math >= 35 && science >= 35 && english >= 35) ? "Pass" : "Fail";

var grade;
if (average >= 90) {
grade = 'A+';
} else if (average >= 80) {
grade = 'A';
} else if (average >= 70) {
grade = 'B';
} else if (average >= 60) {
grade = 'C';
} else if (average >= 50) {
grade = 'D';
} else {
grade = 'F';
}

document.getElementById('totalMarks').value = totalMarks.toFixed(2);
document.getElementById('average').value = average.toFixed(2);
document.getElementById('result').value = result;
document.getElementById('grade').value = grade;
}
</script>
</head>
<body>

<h2>Student Information</h2>
<form>
Math: <input type="number" id="math"><br><br>
Science: <input type="number" id="science"><br><br>
English: <input type="number" id="english"><br><br>
<input type="button" value="Calculate" onclick="calculateResult()">
</form>
<br>

<h2>Result Details</h2>
Total Marks: <input type="text" id="totalMarks" readonly><br><br>
Average: <input type="text" id="average" readonly><br><br>
Result: <input type="text" id="result" readonly><br><br>
Grade: <input type="text" id="grade" readonly>

</body>
</html>

Program 07

<!DOCTYPE html>
<html>
<head>
<title>Employee Information Form</title>
<script>
function calculateSalary() {
var basicSalary = parseFloat(document.getElementById('basicSalary').value);
var allowance = parseFloat(document.getElementById('allowance').value);
var taxRate = parseFloat(document.getElementById('taxRate').value);

var DA = basicSalary * 0.25;


var HRA = basicSalary * 0.15;
var PF = basicSalary * 0.12;

var grossPay = basicSalary + DA + HRA + allowance;

var TAX = (grossPay - PF) * (taxRate / 100);


var deduction = PF + TAX;

var 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('grossPay').value = grossPay.toFixed(2);
document.getElementById('deduction').value = deduction.toFixed(2);
document.getElementById('netPay').value = netPay.toFixed(2);
}
</script>
</head>
<body>

<h2>Employee Information</h2>

<form>
Basic Salary: <input type="number" id="basicSalary"><br><br>
Allowance: <input type="number" id="allowance"><br><br>
Tax Rate(%): <input type="number" id="taxRate"><br><br>
<input type="button" value="Calculate" onclick="calculateSalary()">
</form><br>

<h2>Salary Details</h2>

DA: <input type="text" id="DA" readonly><br><br>


HRA: <input type="text" id="HRA" readonly><br><br>
PF: <input type="text" id="PF" readonly><br><br>
Gross Pay: <input type="text" id="grossPay" readonly><br><br>
Deduction: <input type="text" id="deduction" readonly><br><br>
Net Pay: <input type="text" id="netPay" readonly>

</body>
</html>

Program 08

<?php

// Define an array to map days of the week to background colors


$dayColors = [
'Sunday' => '#ffcccb',
'Monday' => '#ffebcd',
'Tuesday' => '#add8e6',
'Wednesday' => '#98fb98',
'Thursday' => '#f0e68c',
'Friday' => '#dda0dd',
'Saturday' => '#c0c0c0'
];

// Get the current day of the week


$currentDay = date('l'); // Use 'l' for full day name

// Set a default color in case the day is not found


$backgroundColor = '#ffffff'; // Default white color

// Check if the current day exists in the array


if (array_key_exists($currentDay, $dayColors)) {
$backgroundColor = $dayColors[$currentDay]; // Use $currentDay consistently
}
?>

<!DOCTYPE html>
<html>
<head>
<title>Background Color Based on Day of the Week</title>
<style>
body {
background-color: <?php echo $backgroundColor; ?>;
}
</style>
</head>
<body>
<h1>Welcome! Today is <?php echo $currentDay; ?></h1>
</body>
</html>

Program 09

<?php

function isPrime($num) {
if ($num <= 1) {
return false;
}

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


if ($num % $i == 0) {
return false;
}
}

return true;
}

function generatePrimes($n) {
$primeNumbers = [];
$count = 0;
$i = 2;

while ($count < $n) {


if (isPrime($i)) {
$primeNumbers[] = $i;
$count++;
}
$i++;
}

return $primeNumbers;
}

function generateFibonacci($n) {
$fibonacciSeries = [];
$first = 0;
$second = 1;
$fibonacciSeries[] = $first;
$fibonacciSeries[] = $second;

for ($i = 2; $i < $n; $i++) {


$next = $first + $second;
$fibonacciSeries[] = $next;
$first = $second;
$second = $next;
}

return $fibonacciSeries;
}

$numberOfPrimes = 10;
$numberOfTerms = 10;

$primes = generatePrimes($numberOfPrimes);
$fibonacci = generateFibonacci($numberOfTerms);

echo "Prime numbers:";


echo "<pre>" . print_r($primes, true) . "</pre>";

echo "Fibonacci series:";


echo "<pre>" . print_r($fibonacci, true) . "</pre>";
?>
Program 10

<?php

function removeDuplicates($array) {
$result = array_values(array_unique($array));
return $result;
}

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

$uniqueList = removeDuplicates($sortedList);

echo "Original List: ";


print_r($sortedList);
echo "<br>Unique List: ";
print_r($uniqueList);

?>

Program 11

<?php

// Total number of rows for the pattern


$rows = 5;

for ($i = $rows; $i > 0; $i--) {

// Printing leading spaces


for ($j = $rows - $i; $j > 0; $j--) {
echo "&nbsp;"; // Non-breaking space for HTML output
}

// Printing asterisks
for ($k = 0; $k < $i; $k++) {
echo "*";
}

// Move to the next line


echo "<br>";
}

?>
Program 12

<?php

$data = [
['id' => 1, 'name' => 'Srikanth', 'age' => 30],
['id' => 2, 'name' => 'Srinath', 'age' => 35],
['id' => 3, 'name' => 'Srinivas', 'age' => 50],
['id' => 4, 'name' => 'Smayan', 'age' => 45],
['id' => 5, 'name' => 'Saatvik', 'age' => 50],
];

function searchByCriteria($data, $criteria) {


$results = [];

if (!is_array($data) || !is_array($criteria)) {
throw new InvalidArgumentException('Invalid data or criteria format (expected arrays)');
}

foreach ($data as $entry) {


$match = true;

if (!is_array($entry)) {
continue;
}

foreach ($criteria as $key => $value) {


if (!array_key_exists($key, $entry) || $entry[$key] != $value) {
$match = false;
break;
}
}

if ($match) {
$results[] = $entry;
}
}

return $results;
}
$criteria = ['age' => 50];

try {

$searchResults = searchByCriteria($data, $criteria);

echo "Search Results:\n";


print_r($searchResults);
} catch (InvalidArgumentException $e) {
echo "Error: " . $e->getMessage();
}

?>

Program 13

<?php

session_start();

function generateCaptchaCode($length = 6) {

$characters =
'0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ;';

$charactersLength = strlen($characters);

$randomString = '';
for ($i = 0; $i < $length; $i++) {
$randomString .= $characters[rand(0, $charactersLength - 1)];
}

return $randomString;
}

echo "Captcha Code is: " . generateCaptchaCode();

?>
Program 14

<!DOCTYPE html>
<html>
<head>
</head>
<body>

<title>Image Upload and Display</title>

<h1>Upload and Display Images</h1>

<form method="post" enctype="multipart/form-data">

Select image to upload:


<input type="file" name="image" id="image">

<input type="submit" value="Upload Image" name="submit">

</form>

<h2>Uploaded Images:</h2>

<?php
// Connect to the database
$conn = new mysqli("localhost", "root", "", "myDB"); // Update with your credentials

if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

// Function to display uploaded images


function displayImages($conn) {
$sql = "SELECT id, image_name FROM images";
$result = $conn->query($sql);

while ($row = $result->fetch_assoc()) {


echo "<img src='?id=" . $row["id"] . "' alt='" . $row["image_name"] . "'><br>";
}
}

// Image display logic (if GET request with 'id')


if (isset($_GET['id'])) {
$id = intval($_GET['id']);

$stmt = $conn->prepare("SELECT image_type, image_data FROM images WHERE id=?");


$stmt->bind_param("i", $id);
$stmt->execute();
$stmt->bind_result($imageType, $imageData);
$stmt->fetch();

header("Content-Type: " . $imageType);


echo $imageData;
exit;
}

// Image upload logic (if POST request with image)


if ($_SERVER["REQUEST_METHOD"] === "POST" && isset($_FILES["image"])) {
$imageData = file_get_contents($_FILES["image"]["tmp_name"]);
$imageName = $_FILES["image"]["name"];
$imageType = $_FILES["image"]["type"];

$stmt = $conn->prepare("INSERT INTO images (image_name, image_type, image_data)


VALUES (?, ?, ?)");
$stmt->bind_param("sss", $imageName, $imageType, $imageData);
$stmt->execute();
}

// Display uploaded images


displayImages($conn);

// Close the database connection


$conn->close();
?>

</body>
</html>

You might also like