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

CSS PR CODE

The document contains multiple HTML pages with embedded JavaScript functions for various tasks, including arithmetic operations, message displays, even/odd checks, positive/negative checks, array manipulations, string operations, cube calculations, multiplication, switch-case demonstrations, and a simple registration form. Each section includes a button that triggers a JavaScript function to perform the specified operation based on user input. The code examples illustrate fundamental programming concepts using JavaScript in a web environment.

Uploaded by

gaytrimate8
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

CSS PR CODE

The document contains multiple HTML pages with embedded JavaScript functions for various tasks, including arithmetic operations, message displays, even/odd checks, positive/negative checks, array manipulations, string operations, cube calculations, multiplication, switch-case demonstrations, and a simple registration form. Each section includes a button that triggers a JavaScript function to perform the specified operation based on user input. The code examples illustrate fundamental programming concepts using JavaScript in a web environment.

Uploaded by

gaytrimate8
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 37

1) Write a JavaScript to perform Arithmetic Operations.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Arithmetic Operations</title>
</head>
<body>
<h1>Arithmetic Operations</h1>
<button onclick="performArithmeticOperation()">Start Operation</button>

<script>
function performArithmeticOperation() {
let num1 = parseFloat(prompt("Enter the first number: "));
let num2 = parseFloat(prompt("Enter the second number: "));
let operation = prompt("Enter the operation (+, -, *, /, %): ");
let result;

switch (operation) {
case "+":
result = num1 + num2;
break;
case "-":
result = num1 - num2;
break;
case "*":
result = num1 * num2;
break;
case "/":
result = num2 !== 0 ? num1 / num2 : "Error! Division by
zero.";
break;
case "%":
result = num1 % num2;
break;
default:
result = "Invalid operation.";
}

alert(`Result: ${result}`);
document.write(`<h2>Result: ${result}</h2>`);
}
</script>
</body>
</html>
2) Write a JavaScript to display simple messages using JavaScript

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Display Messages</title>
</head>
<body>
<h1>Simple Message Display</h1>
<button onclick="showMessages()">Click to Display Messages</button>

<script>
function showMessages() {
alert("This is a message displayed using alert().");
document.write("<h2>This is a message displayed using
document.write().</h2>");
console.log("This is a message displayed in the browser console
using console.log().");
}
</script>
</body>
</html>

3) Write a JavaScript to find Even and ODD Number


<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Even or Odd Number</title>
</head>
<body>
<h1>Check Even or Odd</h1>
<button onclick="checkEvenOrOdd()">Check Number</button>

<script>
function checkEvenOrOdd() {
let number = parseInt(prompt("Enter a number: "));
if (isNaN(number)) {
document.write("<h2>Please enter a valid number.</h2>");
} else if (number % 2 === 0) {
document.write(`<h2>${number} is Even.</h2>`);
} else {
document.write(`<h2>${number} is Odd.</h2>`);
}
}
</script>
</body>
</html>
4) Write a JavaScript to check the number is positive or negative

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Positive or Negative Number</title>
</head>
<body>
<h1>Check if a Number is Positive or Negative</h1>
<button onclick="checkPositiveOrNegative()">Check Number</button>

<script>
function checkPositiveOrNegative() {
let number = parseFloat(prompt("Enter a number: "));
if (isNaN(number)) {
document.write("<h2>Please enter a valid number.</h2>");
} else if (number > 0) {
document.write(`<h2>${number} is Positive.</h2>`);
} else if (number < 0) {
document.write(`<h2>${number} is Negative.</h2>`);
} else {
document.write("<h2>The number is Zero.</h2>");
}
}
</script>
</body>
</html>

5) Write a JavaScript to perform any 4 Array functions.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Array Functions Example</title>
</head>
<body>
<h1>Array Functions Example</h1>
<button onclick="performArrayFunctions()">Perform Array Operations</button>

<script>
function performArrayFunctions() {
let array = [];
let numElements = parseInt(prompt("How many elements do you want to
add to the array?"));
for (let i = 0; i < numElements; i++) {
let element = prompt(`Enter element ${i + 1}:`);
array.push(element);
}

let operation = prompt("Choose an operation:\n1. push()\n2. pop()\


n3. shift()\n4. unshift()\n5. concat()\n6. slice()\n7. splice()\n8.
forEach()");

switch(operation) {
case "1":
let newElement = prompt("Enter an element to add to the end
of the array using push():");
array.push(newElement);
document.write(`<h3>After push(): ${array}</h3>`);
alert(`Array after push(): ${array}`);
break;
case "2":
let removedElement = array.pop();
document.write(`<h3>After pop(): Removed ${removedElement},
New Array: ${array}</h3>`);
alert(`Array after pop(): ${array}`);
break;
case "3":
let shiftedElement = array.shift();
document.write(`<h3>After shift(): Removed $
{shiftedElement}, New Array: ${array}</h3>`);
alert(`Array after shift(): ${array}`);
break;
case "4":
let unshiftElement = prompt("Enter an element to add to the
beginning of the array using unshift():");
array.unshift(unshiftElement);
document.write(`<h3>After unshift(): ${array}</h3>`);
alert(`Array after unshift(): ${array}`);
break;
case "5":
let newArray = ["a", "b", "c"];
let combinedArray = array.concat(newArray);
document.write(`<h3>After concat(): $
{combinedArray}</h3>`);
alert(`Array after concat(): ${combinedArray}`);
break;
case "6":
let sliceStart = parseInt(prompt("Enter the start index for
slice():"));
let sliceEnd = parseInt(prompt("Enter the end index for
slice():"));
let slicedArray = array.slice(sliceStart, sliceEnd);
document.write(`<h3>After slice(): ${slicedArray}</h3>`);
alert(`Array after slice(): ${slicedArray}`);
break;
case "7":
let spliceStart = parseInt(prompt("Enter the start index
for splice():"));
let spliceDeleteCount = parseInt(prompt("Enter the number
of elements to delete for splice():"));
let insertElements = prompt("Enter elements to insert
(comma separated):").split(",");
let splicedArray = array.splice(spliceStart,
spliceDeleteCount, ...insertElements);
document.write(`<h3>After splice(): ${array}</h3>`);
alert(`Array after splice(): ${array}`);
break;
case "8":
array.forEach((item, index) => {
document.write(`<h3>Item at index ${index}: $
{item}</h3>`);
alert(`Item at index ${index}: ${item}`);
});
break;
default:
alert("Invalid operation choice.");
}
}
</script>
</body>
</html>

6) Write a JavaScript to perform any 4 String functions.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>String Functions Example</title>
</head>
<body>
<h1>String Functions Example</h1>
<button onclick="performStringFunctions()">Perform String
Operations</button>

<script>
function performStringFunctions() {
let inputString = prompt("Enter a string to perform operations
on:");

let operation = prompt("Choose an operation:\n1. charAt()\n2.


concat()\n3. substring()\n4. toUpperCase()\n5. toLowerCase()\n6. indexOf()\n7.
replace()\n8. split()");

switch(operation) {
case "1":
let index = parseInt(prompt("Enter the index to get the
character at that position:"));
let char = inputString.charAt(index);
document.write(`<h3>Character at index ${index}: $
{char}</h3>`);
alert(`Character at index ${index}: ${char}`);
break;
case "2":
let stringToConcat = prompt("Enter a string to
concatenate:");
let concatenatedString =
inputString.concat(stringToConcat);
document.write(`<h3>After concat(): $
{concatenatedString}</h3>`);
alert(`After concat(): ${concatenatedString}`);
break;
case "3":
let startIndex = parseInt(prompt("Enter the start index for
substring():"));
let endIndex = parseInt(prompt("Enter the end index for
substring():"));
let substring = inputString.substring(startIndex,
endIndex);
document.write(`<h3>After substring(): ${substring}</h3>`);
alert(`After substring(): ${substring}`);
break;
case "4":
let upperCaseString = inputString.toUpperCase();
document.write(`<h3>After toUpperCase(): $
{upperCaseString}</h3>`);
alert(`After toUpperCase(): ${upperCaseString}`);
break;
case "5":
let lowerCaseString = inputString.toLowerCase();
document.write(`<h3>After toLowerCase(): $
{lowerCaseString}</h3>`);
alert(`After toLowerCase(): ${lowerCaseString}`);
break;
case "6":
let searchString = prompt("Enter the string to find its
index:");
let indexOfString = inputString.indexOf(searchString);
document.write(`<h3>Index of "${searchString}": $
{indexOfString}</h3>`);
alert(`Index of "${searchString}": ${indexOfString}`);
break;
case "7":
let oldString = prompt("Enter the substring to replace:");
let newString = prompt("Enter the new substring to replace
with:");
let replacedString = inputString.replace(oldString,
newString);
document.write(`<h3>After replace(): $
{replacedString}</h3>`);
alert(`After replace(): ${replacedString}`);
break;
case "8":
let separator = prompt("Enter the separator to split the
string by:");
let splitString = inputString.split(separator);
document.write(`<h3>After split(): ${splitString}</h3>`);
alert(`After split(): ${splitString}`);
break;
default:
alert("Invalid operation choice.");
}
}
</script>
</body>
</html>

7) Write a JavaScript to find cube of a number using function.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Cube of a Number</title>
</head>
<body>
<h1>Calculate Cube of a Number</h1>
<button onclick="calculateCube()">Calculate Cube</button>

<script>
function calculateCube() {
let num = parseFloat(prompt("Enter a number to find its cube:"));
let cube = Math.pow(num, 3);
document.write(`<h3>The cube of ${num} is ${cube}</h3>`);
alert(`The cube of ${num} is ${cube}`);
}
</script>
</body>
</html>

8) Write a JavaScript to find multiplication of a number using function

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Multiplication of a Number</title>
</head>
<body>
<h1>Multiply a Number</h1>
<button onclick="multiplyNumber()">Multiply Number</button>

<script>
function multiplyNumber() {
let num = parseFloat(prompt("Enter a number to multiply:"));
let multiplier = parseFloat(prompt("Enter the multiplier:"));
let result = num * multiplier;
document.write(`<h3>${num} multiplied by ${multiplier} is $
{result}</h3>`);
alert(`${num} multiplied by ${multiplier} is ${result}`);
}
</script>
</body>
</html>

9) Write a JavaScript to demonstrate use of Switch-case. Perform any 3 cases. Assume suitable Data

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Switch-Case Example</title>
</head>
<body>
<h1>Switch-Case Example</h1>
<button onclick="demonstrateSwitchCase()">Perform Operations</button>

<script>
function demonstrateSwitchCase() {
let choice = prompt("Choose an operation:\n1. Check if a number is
positive, negative, or zero\n2. Find the day of the week\n3. Perform arithmetic
operation (addition, subtraction, multiplication)");

switch(choice) {
case "1":
let num = parseFloat(prompt("Enter a number to check if
it's positive, negative, or zero:"));
if (num > 0) {
alert("The number is positive.");
document.write("<h3>The number is positive.</h3>");
} else if (num < 0) {
alert("The number is negative.");
document.write("<h3>The number is negative.</h3>");
} else {
alert("The number is zero.");
document.write("<h3>The number is zero.</h3>");
}
break;

case "2":
let dayNumber = parseInt(prompt("Enter a number (1-7) to
find the corresponding day of the week:"));
let day;
switch(dayNumber) {
case 1: day = "Monday"; break;
case 2: day = "Tuesday"; break;
case 3: day = "Wednesday"; break;
case 4: day = "Thursday"; break;
case 5: day = "Friday"; break;
case 6: day = "Saturday"; break;
case 7: day = "Sunday"; break;
default: day = "Invalid day number!"; break;
}
alert(`The day of the week is: ${day}`);
document.write(`<h3>The day of the week is: ${day}</h3>`);
break;

case "3":
let operation = prompt("Choose an operation: (+ for
addition, - for subtraction, * for multiplication)");
let num1 = parseFloat(prompt("Enter the first number:"));
let num2 = parseFloat(prompt("Enter the second number:"));
let result;

switch(operation) {
case "+":
result = num1 + num2;
alert(`The result of addition is: ${result}`);
document.write(`<h3>The result of addition is: $
{result}</h3>`);
break;
case "-":
result = num1 - num2;
alert(`The result of subtraction is: ${result}`);
document.write(`<h3>The result of subtraction is: $
{result}</h3>`);
break;
case "*":
result = num1 * num2;
alert(`The result of multiplication is: $
{result}`);
document.write(`<h3>The result of multiplication
is: ${result}</h3>`);
break;
default:
alert("Invalid operation!");
document.write("<h3>Invalid operation!</h3>");
}
break;
default:
alert("Invalid choice! Please select 1, 2, or 3.");
document.write("<h3>Invalid choice! Please select 1, 2, or
3.</h3>");
}
}
</script>
</body>
</html>

10) Create a webpage to design simple registration form with all major controls.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Registration Form</title>
<style>
body {
font-family: Arial, sans-serif;
margin: 0;
padding: 0;
background-color: #f2f2f2;
}
.container {
width: 50%;
margin: 0 auto;
padding: 20px;
background-color: white;
box-shadow: 0px 0px 10px 2px rgba(0, 0, 0, 0.1);
margin-top: 50px;
}
h2 {
text-align: center;
}
label {
font-size: 14px;
margin-top: 10px;
}
input[type="text"], input[type="password"], input[type="email"], select,
input[type="file"] {
width: 100%;
padding: 8px;
margin-top: 5px;
margin-bottom: 15px;
border: 1px solid #ccc;
border-radius: 4px;
}
input[type="radio"], input[type="checkbox"] {
margin: 10px 5px;
}
button {
width: 48%;
padding: 10px;
font-size: 14px;
background-color: #4CAF50;
color: white;
border: none;
border-radius: 4px;
cursor: pointer;
margin-top: 10px;
}
button:hover {
background-color: #45a049;
}
.form-group {
margin-bottom: 20px;
}
.form-footer {
text-align: center;
}
#imagePreview {
margin-top: 10px;
max-width: 200px;
max-height: 200px;
border: 1px solid #ddd;
padding: 5px;
}
</style>
</head>
<body>
<div class="container">
<h2>Registration Form</h2>
<form id="registrationForm" onsubmit="return handleSubmit()">
<div class="form-group">
<label for="fname">First Name:</label>
<input type="text" id="fname" name="fname" required>
</div>

<div class="form-group">
<label for="lname">Last Name:</label>
<input type="text" id="lname" name="lname" required>
</div>

<div class="form-group">
<label for="email">Email:</label>
<input type="email" id="email" name="email" required>
</div>
<div class="form-group">
<label for="password">Password:</label>
<input type="password" id="password" name="password" required>
</div>

<div class="form-group">
<label for="gender">Gender:</label><br>
<input type="radio" id="male" name="gender" value="male" required>
<label for="male">Male</label><br>
<input type="radio" id="female" name="gender" value="female"
required>
<label for="female">Female</label>
</div>

<div class="form-group">
<label for="dob">Date of Birth:</label>
<input type="date" id="dob" name="dob" required>
</div>

<div class="form-group">
<label for="country">Country:</label>
<select id="country" name="country" required>
<option value="usa">USA</option>
<option value="india">India</option>
<option value="uk">UK</option>
<option value="canada">Canada</option>
<option value="australia">Australia</option>
</select>
</div>

<div class="form-group">
<label for="terms">Agree to terms:</label>
<input type="checkbox" id="terms" name="terms" required>
<label for="terms">I agree to the terms and conditions</label>
</div>

<div class="form-group">
<label for="profileImage">Upload Profile Image:</label>
<input type="file" id="profileImage" name="profileImage"
accept="image/*" onchange="previewImage(event)">
<div id="imagePreview"></div>
</div>

<div class="form-footer">
<button type="submit">Submit</button>
<button type="reset" onclick="resetForm()">Reset</button>
</div>
</form>
</div>

<script>
function previewImage(event) {
const file = event.target.files[0];
if (file) {
const reader = new FileReader();
reader.onload = function(e) {
const imagePreview = document.getElementById('imagePreview');
imagePreview.innerHTML = `<img src="${e.target.result}"
alt="Profile Image" style="width: 100%; height: auto;">`;
};
reader.readAsDataURL(file);
}
}

function resetForm() {
document.getElementById("imagePreview").innerHTML = "";
}

function handleSubmit() {
alert("Form submitted successfully!");
resetForm();
document.getElementById("registrationForm").reset();
return false;
}
</script>
</body>
</html>

11) Write a JavaScript to demonstrate use of onBlur Event.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>onBlur Event Example</title>
</head>
<body>
<h2>onBlur Event Example</h2>
<form>
<label for="username">Username:</label><br>
<input type="text" id="username" onblur="validateUsername()"><br>
<span id="usernameError" style="color: red;"></span><br><br>

<label for="email">Email:</label><br>
<input type="email" id="email" onblur="validateEmail()"><br>
<span id="emailError" style="color: red;"></span><br><br>

<button type="button" onclick="submitForm()">Submit</button>


</form>

<script>
function validateUsername() {
const username = document.getElementById("username").value;
const errorDiv = document.getElementById("usernameError");
if (username.trim() === "") {
errorDiv.textContent = "Username cannot be empty.";
} else if (username.length < 3) {
errorDiv.textContent = "Username must be at least 3 characters.";
} else {
errorDiv.textContent = "";
}
}

function validateEmail() {
const email = document.getElementById("email").value;
const errorDiv = document.getElementById("emailError");
const emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
if (email.trim() === "") {
errorDiv.textContent = "Email cannot be empty.";
} else if (!emailPattern.test(email)) {
errorDiv.textContent = "Invalid email format.";
} else {
errorDiv.textContent = "";
}
}

function submitForm() {
const usernameError = document.getElementById("usernameError").textContent;
const emailError = document.getElementById("emailError").textContent;

if (usernameError || emailError) {
alert("Please fix the errors before submitting.");
} else {
alert("Form submitted successfully!");
}
}
</script>
</body>
</html>

12) Write a JavaScript to demonstrate use of onFocus Event.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>onFocus Event Example</title>
</head>
<body>
<h2>onFocus Event Example</h2>
<form>
<label for="username">Username:</label><br>
<input type="text" id="username" onfocus="showHelp('Enter your username.')" onblur="hideHelp()"><br><br>

<label for="email">Email:</label><br>
<input type="email" id="email" onfocus="showHelp('Enter a valid email address.')" onblur="hideHelp()"><br><br>

<div id="helpText" style="color: blue; font-size: 14px;"></div>


</form>

<script>
function showHelp(message) {
const helpDiv = document.getElementById("helpText");
helpDiv.textContent = message;
}

function hideHelp() {
const helpDiv = document.getElementById("helpText");
helpDiv.textContent = "";
}
</script>
</body>
</html>

13) Write a JavaScript to demonstrate use of onChange Event.


<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>onChange Event Example</title>
</head>
<body>
<h2>onChange Event Example</h2>
<form>
<label for="colorSelect">Select a color:</label><br>
<select id="colorSelect" onchange="displaySelectedColor()">
<option value="">--Choose a color--</option>
<option value="Red">Red</option>
<option value="Green">Green</option>
<option value="Blue">Blue</option>
<option value="Yellow">Yellow</option>
</select>
<p id="output" style="font-weight: bold; margin-top: 10px;"></p>
</form>

<script>
function displaySelectedColor() {
const selectedColor = document.getElementById("colorSelect").value;
const output = document.getElementById("output");
if (selectedColor) {
output.textContent = `You selected: ${selectedColor}`;
} else {
output.textContent = "";
}
}
</script>
</body>
</html>

14) Write a JavaScript to demonstrate any 4 Date class functions.


<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Date Class Functions</title>
</head>
<body>
<h2>Date Class Functions Example</h2>
<button onclick="showDateInfo()">Show Date Information</button>
<p id="output"></p>

<script>
function showDateInfo() {
const currentDate = new Date();

const currentDay = currentDate.getDay(); // Gets the day of the week (0-6)


const currentMonth = currentDate.getMonth(); // Gets the month (0-11)
const currentTime = currentDate.toLocaleTimeString(); // Formats the time in local format
const fullYear = currentDate.getFullYear(); // Gets the full year

const days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];


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

const output = `
<strong>Current Date Information:</strong><br>
Today is: ${days[currentDay]}<br>
Current Month: ${months[currentMonth]}<br>
Current Time: ${currentTime}<br>
Current Year: ${fullYear}
`;

document.getElementById("output").innerHTML = output;
}
</script>
</body>
</html>

15) Write a JavaScript to demonstrate any 4 Math class functions


<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Math Class Functions</title>
</head>
<body>
<h2>Math Class Functions Example</h2>
<button onclick="showMathFunctions()">Show Math Operations</button>
<p id="output"></p>

<script>
function showMathFunctions() {
const number = 25.7;
const negativeNumber = -8;

const squareRoot = Math.sqrt(number);


const roundedValue = Math.round(number);
const absoluteValue = Math.abs(negativeNumber);
const randomValue = Math.random(); // Generates a random number between 0 and 1

const output = `
<strong>Math Operations:</strong><br>
Square Root of ${number}: ${squareRoot}<br>
Rounded Value of ${number}: ${roundedValue}<br>
Absolute Value of ${negativeNumber}: ${absoluteValue}<br>
Random Number (0 to 1): ${randomValue.toFixed(4)}
`;

document.getElementById("output").innerHTML = output;
}
</script>
</body>
</html>

16) Write a JavaScript to demonstrate use of Window.open() method.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Window.open() Example</title>
</head>
<body>
<h2>Window.open() Method Example</h2>
<button onclick="openNewWindow()">Open Google</button>
<button onclick="openCustomWindow()">Open Custom Window</button>

<script>
function openNewWindow() {
window.open("https://www.google.com", "_blank");
}

function openCustomWindow() {
window.open(
"https://www.example.com",
"CustomWindow",
"width=600,height=400,top=100,left=100,resizable=yes,scrollbars=yes"
);
}
</script>
</body>
</html>

17) Write a JavaScript to create a Cookie.


<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Create and Display Cookie</title>
</head>
<body>
<h2>Cookie Example</h2>
<button onclick="createCookie()">Create Cookie</button>
<button onclick="displayCookie()">Display Cookie</button>
<p id="output"></p>

<script>
function createCookie() {
const cookieName = "username";
const cookieValue = prompt("Enter your name:");
const expiryDate = new Date();
expiryDate.setTime(expiryDate.getTime() + (7 * 24 * 60 * 60 * 1000)); // Cookie expires in 7 days
document.cookie = `${cookieName}=${cookieValue}; expires=${expiryDate.toUTCString()}; path=/`;
alert("Cookie created successfully!");
}

function displayCookie() {
const cookies = document.cookie;
const output = cookies ? `Cookies: ${cookies}` : "No cookies found.";
document.getElementById("output").textContent = output;
}
</script>
</body>
</html>

18) Write a JavaScript to find a character is vowel or not using regular Expression.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Vowel Check with Regex</title>
</head>
<body>
<h2>Check if a Character is a Vowel</h2>
<button onclick="checkVowel()">Check Vowel</button>
<p id="output"></p>

<script>
function checkVowel() {
const char = prompt("Enter a single character:").toLowerCase();
const isVowel = /^[aeiou]$/.test(char);

if (char.length !== 1) {
document.getElementById("output").textContent = "Please enter only one character.";
} else if (isVowel) {
document.getElementById("output").textContent = `${char} is a vowel.`;
} else {
document.getElementById("output").textContent = `${char} is not a vowel.`;
}
}
</script>
</body>
</html>

19) Write a JavaScript to find a character is in upper case or not using regular Expression.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Check Uppercase Character</title>
</head>
<body>
<h2>Check if a Character is Uppercase</h2>
<button onclick="checkUppercase()">Check Uppercase</button>
<p id="output"></p>

<script>
function checkUppercase() {
const char = prompt("Enter a single character:");
const isUppercase = /^[A-Z]$/.test(char);

if (char.length !== 1) {
document.getElementById("output").textContent = "Please enter only one character.";
} else if (isUppercase) {
document.getElementById("output").textContent = `${char} is an uppercase letter.`;
} else {
document.getElementById("output").textContent = `${char} is not an uppercase letter.`;
}
}
</script>
</body>
</html>
20) Write a JavaScript to find a character is in lower case or not using regular Expression.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Check Lowercase Character</title>
</head>
<body>
<h2>Check if a Character is Lowercase</h2>
<button onclick="checkLowercase()">Check Lowercase</button>
<p id="output"></p>

<script>
function checkLowercase() {
const char = prompt("Enter a single character:");
const isLowercase = /^[a-z]$/.test(char);

if (char.length !== 1) {
document.getElementById("output").textContent = "Please enter only one character.";
} else if (isLowercase) {
document.getElementById("output").textContent = `${char} is a lowercase letter.`;
} else {
document.getElementById("output").textContent = `${char} is not a lowercase letter.`;
}
}
</script>
</body>
</html>

21) Create a webpage with Rollover Effect


<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Simple Rollover Effect</title>
</head>
<body>

<h2>Hover Over the Image to Change</h2>

<img id="fruit" src="mango.jpg" alt="Fruit" width="300" height="200"


onmouseover="this.src='apple.jpg'"
onmouseout="this.src='banana.jpg'">

</body>
</html>

22) Develop a webpage for implementing pulldown menu. Assume suitable data.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Simple Pulldown Menu</title>
<style>
body {
font-family: Arial, sans-serif;
padding: 20px;
}

/* Style the dropdown container */


.dropdown {
position: relative;
display: inline-block;
}

/* Style the button that opens the dropdown */


.dropbtn {
background-color: #4CAF50;
color: white;
padding: 10px 20px;
font-size: 16px;
border: none;
cursor: pointer;
}

/* Change the color of the button when you hover over it */


.dropbtn:hover {
background-color: #45a049;
}

/* The dropdown content (hidden by default) */


.dropdown-content {
display: none;
position: absolute;
background-color: #f9f9f9;
min-width: 160px;
box-shadow: 0px 8px 16px rgba(0, 0, 0, 0.2);
z-index: 1;
}
/* Links inside the dropdown */
.dropdown-content a {
color: black;
padding: 12px 16px;
text-decoration: none;
display: block;
}

/* Change the color of links when you hover over them */


.dropdown-content a:hover {
background-color: #ddd;
}

/* Show the dropdown menu when the user clicks on the button */
.dropdown:hover .dropdown-content {
display: block;
}
</style>
</head>
<body>

<h2>Simple Pulldown Menu Example</h2>

<p>Click the button to see the dropdown menu with several options.</p>

<!-- Dropdown Menu -->


<div class="dropdown">
<button class="dropbtn">Select Fruit</button>
<div class="dropdown-content">
<a href="#">Apple</a>
<a href="#">Banana</a>
<a href="#">Mango</a>
<a href="#">Orange</a>
<a href="#">Grapes</a>
</div>
</div>

<script>
// You can add functionality to handle selection, if needed
document.querySelectorAll('.dropdown-content a').forEach(item => {
item.addEventListener('click', event => {
alert('You selected: ' + event.target.innerText);
});
});
</script>

</body>
</html>

23) Develop a webpage for disabling a mouse right click.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Disable Right Click</title>
</head>
<body>

<h2>Right Click is Disabled on This Page</h2>


<p>Try right-clicking anywhere on this page to see that it is disabled.</p>

<script>
// Disable right-click by preventing the default context menu
document.addEventListener('contextmenu', function(e) {
e.preventDefault();
alert('Right-click is disabled on this page!');
});
</script>

</body>
</html>

24) Develop a webpage for creating rotating (changing) banner.

<html >
<head>
<title>Banner Ads</title>
<script>
Banners = new Array('apple.jpg','mango.jpg','banana.jpg');
CurrentBanner = 0;
function DisplayBanners()
{
if (document.images);
{
CurrentBanner++;
if (CurrentBanner == Banners.length)
{
CurrentBanner = 0;
}
document.RotateBanner.src= Banners[CurrentBanner];
setTimeout("DisplayBanners()",1000);
}
}
</script>
</head>
<body onload="DisplayBanners()" >
<center>
<img src="1.jpg" width="400"
height="75" name="RotateBanner" />
</center>
</body>
</html>

25) Develop a webpage for creating slideshow using banner.

<html>
<head>
<title>Banner Slideshow</title>
<script>

var pics = new Array('apple.jpg', 'mango.jpg', 'banana.jpg');


var count = 0;

function slideshow(status) {
if (document.images) {
count = count + status;

if (count > (pics.length - 1)) {


count = 0;
}
if (count < 0) {
count = pics.length - 1;
}

document.img1.src = pics[count];
}
}

function autoRotateBanners() {
count++;
if (count == pics.length) {
count = 0;
}
document.img1.src = pics[count];

setTimeout(autoRotateBanners, 3000);
}

window.onload = function() {
autoRotateBanners();
};
</script>
</head>
<body>
<center>
<h2>Image Slideshow with Auto Rotation</h2>
<img src="apple.jpg" width="400" height="75" name="img1">
<br>

<input type="button" value="Next" onclick="slideshow(1)">


<input type="button" value="Back" onclick="slideshow(-1)">
</center>
</body>
</html>

26) Accept full name of user in single text box and separate first, middle and last name from accepted name and display it in
capitalized form.

<!DOCTYPE html>

<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-
scale=1.0">
<title>Full Name Splitter</title>
<script>
function processName() {
// Get the full name entered by the user
let fullName = document.getElementById("fullName").value;

// Trim any extra spaces and split the full name into
parts
let nameParts = fullName.trim().split(/\s+/); // Split by
any space

// Check if the user has entered a first, middle, and last


name
let firstName = nameParts[0] || '';
let middleName = nameParts.length > 2 ? nameParts.slice(1,
nameParts.length - 1).join(' ') : '';
let lastName = nameParts[nameParts.length - 1] || '';

// Capitalize the first letter of each part and join them


back
firstName = firstName.charAt(0).toUpperCase() +
firstName.slice(1).toLowerCase();
middleName = middleName.charAt(0).toUpperCase() +
middleName.slice(1).toLowerCase();
lastName = lastName.charAt(0).toUpperCase() +
lastName.slice(1).toLowerCase();

// Display the results in the designated areas


document.getElementById("firstName").innerText = "First
Name: " + firstName;
document.getElementById("middleName").innerText = "Middle
Name: " + middleName;
document.getElementById("lastName").innerText = "Last
Name: " + lastName;
}
</script>
</head>
<body>

<h2>Enter Full Name</h2>


<input type="text" id="fullName" placeholder="Enter your full name
here">
<button onclick="processName()">Submit</button>

<h3>Processed Name:</h3>
<p id="firstName"></p>
<p id="middleName"></p>
<p id="lastName"></p>

</body>
</html>

27) WAP to replace following specified string value with another value in the string
String = “I will fail”Replace = “fail” by “pass”
<html>
<head>
<body>
<script>
var myStr = 'I will fail';
var newStr = myStr.replace(fail, "pass");
document.write(newStr);
</script>
</body>
</head>
</html>
28) Create a slideshow with the group of three images, also simulate the next and previous transition between slides in your
JavaScript.

<html>
<head>
<title>Banner Slideshow</title>
<script>

var pics = new Array('apple.jpg', 'mango.jpg', 'banana.jpg');


var count = 0;

function slideshow(status) {
if (document.images) {
count = count + status;

if (count > (pics.length - 1)) {


count = 0;
}
if (count < 0) {
count = pics.length - 1;
}

document.img1.src = pics[count];
}
}

function autoRotateBanners() {
count++;
if (count == pics.length) {
count = 0;
}
document.img1.src = pics[count];

setTimeout(autoRotateBanners, 3000);
}

window.onload = function() {
autoRotateBanners();
};
</script>
</head>
<body>
<center>
<h2>Image Slideshow with Auto Rotation</h2>
<img src="apple.jpg" width="400" height="75" name="img1">
<br>

<input type="button" value="Next" onclick="slideshow(1)">


<input type="button" value="Back" onclick="slideshow(-1)">
</center>
</body>
</html>

29) Write HTML Script that displays drop-down-list containing options New Delhi, Mumbai, Bangalore. Write proper JavaScript
such that when the user selects any options corresponding description of about 20 words and image of the city appear in table which
appears below on the same page.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-
scale=1.0">
<title>City Info</title>
<style>
table {
border-collapse: collapse;
width: 50%;
margin-top: 20px;
}
table, th, td {
border: 1px solid black;
}
th, td {
padding: 10px;
text-align: center;
}
img {
width: 150px;
height: 100px;
}
</style>
<script>
function displayCityInfo() {
const cityData = {
"New Delhi": {
description: "New Delhi is the capital of India,
known for its rich history and vibrant culture.",
image: "delhi.jpg"
},
"Mumbai": {
description: "Mumbai is India's financial hub,
famous for Bollywood and the Gateway of India.",
image: "mumbai.jpg"
},
"Bangalore": {
description: "Bangalore is the IT hub of India,
known for its parks and pleasant weather.",
image: "bangalore.jpg"
}
};

const city =
document.getElementById("cityDropdown").value;
const table = document.getElementById("cityTable");
const cityInfo = cityData[city];

if (cityInfo) {
table.innerHTML = `
<tr>
<th>City</th>
<th>Description</th>
<th>Image</th>
</tr>
<tr>
<td>${city}</td>
<td>${cityInfo.description}</td>
<td><img src="${cityInfo.image}" alt="$
{city}"></td>
</tr>
`;
}
}
</script>
</head>
<body>
<h2>Select a City</h2>
<select id="cityDropdown" onchange="displayCityInfo()">
<option value="">-- Select a City --</option>
<option value="New Delhi">New Delhi</option>
<option value="Mumbai">Mumbai</option>
<option value="Bangalore">Bangalore</option>
</select>

<table id="cityTable">
<tr>
<th>City</th>
<th>Description</th>
<th>Image</th>
</tr>
</table>

</body>
</html>

30) Write a JavaScript function that checks whether a passed string is palindrome or not.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-
scale=1.0">
<title>Palindrome Checker</title>
<script>
function isPalindrome() {
let inputString =
document.getElementById("inputText").value.trim();
let normalizedString =
inputString.toLowerCase().replace(/[^a-z0-9]/g, '');
let reversedString =
normalizedString.split('').reverse().join('');

if (normalizedString === reversedString) {


document.getElementById("result").textContent = `"$
{inputString}" is a Palindrome!`;
} else {
document.getElementById("result").textContent = `"$
{inputString}" is not a Palindrome.`;
}
}
</script>
</head>
<body>
<h2>Palindrome Checker</h2>
<label for="inputText">Enter a string:</label>
<input type="text" id="inputText">
<button onclick="isPalindrome()">Check</button>
<p id="result"></p>
</body>
</html>

31) Write a HTML script which displays 2 radio buttons to the users for fruits and vegetables and 1 option list. When user select
fruits radio button option list should present only fruits names to the user & when user select vegetable radio button option list
should present only vegetable names to the user

<html>
<head>
<title>HTML Form</title>
<script language="javascript" type="text/javascript">
function updateList(ElementValue) {
with (document.forms.myform) {
if (ElementValue == 1) {
optionList[0].text = "Mango";
optionList[0].value = 1;
optionList[1].text = "Banana";
optionList[1].value = 2;
optionList[2].text = "Apple";
optionList[2].value = 3;
}
if (ElementValue == 2) {
optionList[0].text = "Potato";
optionList[0].value = 1;
optionList[1].text = "Cabbage";
optionList[1].value = 2;
optionList[2].text = "Onion";
optionList[2].value = 3;
}
}
}
</script>
</head>
<body>
<form name="myform" action="" method="post">
<p>
<select name="optionList" size="2">
<option value="1">Mango</option>
<option value="2">Banana</option>
<option value="3">Apple</option>
</select>

<br />
<input
type="radio"
name="grp1"
value="1"
checked="true"
onclick="updateList(this.value)"
/>Fruits
<input
type="radio"
name="grp1"
value="2"
onclick="updateList(this.value)"
/>Vegetables
<br />
<input name="Reset" value="Reset" type="reset" />
</p>
</form>
</body>
</html>

32) Write a Java script to modify the status bar using on MouseOver and on MouseOut with links. When the user moves his mouse
over the links, it will display “MSBTE” in the status bar. When the user moves his mouse away from the link the status bar will
display nothing.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Status Bar Modification</title>
<script>
function showStatus() {
window.status = "MSBTE";
}

function clearStatus() {
window.status = "";
}
</script>
</head>
<body>
<h2>Status Bar Modification</h2>
<p>Hover over the links below to see the status bar message:</p>
<a href="https://example.com" onmouseover="showStatus()" onmouseout="clearStatus()">Example Link
1</a><br>
<a href="https://msbte.org.in" onmouseover="showStatus()" onmouseout="clearStatus()">Example Link
2</a><br>
<a href="https://google.com" onmouseover="showStatus()" onmouseout="clearStatus()">Example Link
3</a>
</body>
</html>

33) Write a javascript that displays all properties of window object

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Window Object Properties</title>
<style>
body {
font-family: Arial, sans-serif;
}
pre {
background-color: #f4f4f4;
padding: 10px;
border: 1px solid #ddd;
max-height: 300px;
overflow-y: auto;
}
</style>
<script>
function displayWindowProperties() {
const properties = Object.getOwnPropertyNames(window).sort();
document.getElementById("output").textContent = properties.join("\n");
}
</script>
</head>
<body onload="displayWindowProperties()">
<h2>Properties of the Window Object</h2>
<pre id="output"></pre>
</body>
</html>

34) Write a function that prompts the user for a color and uses what they select to set the background color of the new webpage
opened.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Set Background Color</title>
<script>
function setBackgroundColor() {
const color = prompt("Enter a color (e.g., red, blue, #123456, rgb(255, 255, 255)):");
if (color) {
const newWindow = window.open("", "_blank", "width=400,height=400");

newWindow.document.body.style.backgroundColor = color;
newWindow.document.body.style.fontFamily = "Arial, sans-serif";
newWindow.document.body.style.textAlign = "center";
newWindow.document.body.style.padding = "20px";

const heading = newWindow.document.createElement("h1");


heading.textContent = "Background Color Set";
newWindow.document.body.appendChild(heading);

const paragraph = newWindow.document.createElement("p");


paragraph.innerHTML = `The background color is <strong>${color}</strong>.`;
newWindow.document.body.appendChild(paragraph);
} else {
alert("No color entered. Background color was not set.");
}
}
</script>
</head>
<body>
<h2>Change Background Color</h2>
<button onclick="setBackgroundColor()">Set Background Color</button>
</body>
</html>

35) Write a JavaScript program that create a scrolling text on the status line of a window
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Scrolling Status Text</title>
<script>
let message = "Welcome to the scrolling status bar demo! ";
let position = 0;

function scrollStatusBar() {

window.status = message.substring(position) + message.substring(0, position);


position = (position + 1) % message.length;
setTimeout(scrollStatusBar, 200);
}
</script>
</head>
<body onload="scrollStatusBar()">
<h1>Scrolling Text in the Status Bar</h1>
<p>The text will scroll continuously in the browser's status bar.</p>
</body>
</html>

36) Develop a JavaScript Program to Create Rotating Banner Ads with URL Links. Create a slideshow with the group of four
images, also simulate the next and previous transition between slides in your JavaScript

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Rotating Banner Ads</title>
<script>
const banners = ['mango.jpg', 'apple.jpg', 'banana.jpg', 'delhi.jpg'];
const bannerLinks = [
'https://www.google.com',
'https://www.vpt.edu.in',
'https://www.msbte.org.in',
'https://www.wikipedia.org'
];
let currentBanner = 0;
let autoRotate = null; // Ensure global scope

function updateBanner() {
const banner = document.getElementById('RotateBanner');
banner.src = banners[currentBanner];
banner.parentElement.href = bannerLinks[currentBanner];
}

function nextBanner() {
currentBanner = (currentBanner + 1) % banners.length;
updateBanner();
}

function prevBanner() {
currentBanner = (currentBanner - 1 + banners.length) % banners.length;
updateBanner();
}

function startAutoRotate() {
if (!autoRotate) { // Prevent multiple intervals
autoRotate = setInterval(nextBanner, 2000);
}
}

function stopAutoRotate() {
if (autoRotate) {
clearInterval(autoRotate);
autoRotate = null; // Reset to allow restart
}
}

function init() {
updateBanner();
startAutoRotate();
}
</script>
</head>
<body onload="init()">
<center>
<h1>Rotating Banner Ads</h1>
<a href="#" target="_blank">
<img id="RotateBanner" src="1.jpg" alt="Banner Ad" width="400" height="200">
</a>
<br>
<button onclick="prevBanner()">Previous</button>
<button onclick="nextBanner()">Next</button>
<button onclick="startAutoRotate()">Start Auto Rotate</button>
<button onclick="stopAutoRotate()">Stop Auto Rotate</button>
</center>
</body>
</html>

37) Write a webpage that accepts Username and adharcard as input texts. When the user enters adhaarcard number ,the JavaScript
validates card number and diplays whether card number is valid or not. (Assume valid adhaar card format to be nnnn.nnnn.nnnn or
nnnn-nnnn-nnnn)

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Aadhaar Card Validation</title>
<script>
function validateAadhaarCard() {
var aadhaar = document.getElementById("aadhaar").value;
var username = document.getElementById("username").value;

// Regular expression to validate Aadhaar number (nnnn.nnnn.nnnn or nnnn-nnnn-


nnnn)
var aadhaarRegex = /^\d{4}[-.\s]?\d{4}[-.\s]?\d{4}$/;

if (aadhaar.match(aadhaarRegex)) {
document.getElementById("result").innerHTML = username + ", your Aadhaar
card number is valid.";
document.getElementById("result").style.color = "green";
} else {
document.getElementById("result").innerHTML = "Invalid Aadhaar card number.
Please enter a valid number.";
document.getElementById("result").style.color = "red";
}
}
</script>
</head>
<body>
<h2>Aadhaar Card Validation</h2>
<form onsubmit="event.preventDefault(); validateAadhaarCard();">
<label for="username">Username: </label>
<input type="text" id="username" name="username" required>
<br><br>

<label for="aadhaar">Enter Aadhaar Card Number: </label>


<input type="text" id="aadhaar" name="aadhaar" required>
<br><br>

<input type="submit" value="Validate Aadhaar">


</form>

<p id="result"></p>
</body>
</html>
38) Write HTML Script that displays textboxes for accepting Name, middlename, Surname of the user and a Submit button. Write
proper JavaScript such that when the user clicks on submit button: i) All texboxes must get disabled and change the color to “RED”
and with respective labels.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Disable Textboxes and Change Color</title>
<script>
function disableTextboxes() {
// Get all the input fields and labels
var nameInput = document.getElementById("name");
var middleNameInput = document.getElementById("middleName");
var surnameInput = document.getElementById("surname");

var nameLabel = document.getElementById("nameLabel");


var middleNameLabel = document.getElementById("middleNameLabel");
var surnameLabel = document.getElementById("surnameLabel");

// Disable all the input fields


nameInput.disabled = true;
middleNameInput.disabled = true;
surnameInput.disabled = true;

// Change background color to red for each textbox


nameInput.style.backgroundColor = "red";
middleNameInput.style.backgroundColor = "red";
surnameInput.style.backgroundColor = "red";

// Change label color to red


nameLabel.style.color = "red";
middleNameLabel.style.color = "red";
surnameLabel.style.color = "red";
}
</script>
</head>
<body>
<h2>Enter Your Name Details</h2>

<form id="userForm">
<label id="nameLabel" for="name">First Name:</label>
<input type="text" id="name" name="name" required>
<br><br>

<label id="middleNameLabel" for="middleName">Middle Name:</label>


<input type="text" id="middleName" name="middleName">
<br><br>

<label id="surnameLabel" for="surname">Surname:</label>


<input type="text" id="surname" name="surname" required>
<br><br>

<input type="submit" value="Submit" onclick="event.preventDefault();


disableTextboxes();">
</form>
</body>
</html>
39) Write a JavaScript program to find the area of a triangle where lengths of the three of its sides are 5, 6, and 7.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Triangle Area</title>
<script>
function calculateArea() {
// Lengths of the three sides
var a = 5;
var b = 6;
var c = 7;

// Semi-perimeter of the triangle


var s = (a + b + c) / 2;

// Area calculation using Heron's Formula


var area = Math.sqrt(s * (s - a) * (s - b) * (s - c));

// Display the result


document.getElementById("result").innerHTML = "The area of the triangle is: " +
area.toFixed(2) + " square units.";
}
</script>
</head>
<body onload="calculateArea()">
<h2>Area of a Triangle</h2>
<p id="result"></p>
</body>
</html>

40) Write a script for creating following frame structure

Frame1
Frame2
FRUITS Frame3
FLOWER
SCITIES
Fruits, Flowers and Cities are links to the webpage fruits.html, flowers.html, cities.html respectively. When these links are clicked
corresponding data appears in “FRAME3”

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Frames Example</title>
</head>
<body>
<frameset cols="25%, 75%">
<!-- Left Frame (Frame 1) with links -->
<frame src="frame2.html" name="frame1" />

<!-- Right Frame (Frame 3) to display content -->


<frame src="default.html" name="frame3" />
</frameset>
</body>
</html>

Contents of frame2.html (Frame with links):

This file contains the links (Fruits, Flowers, and Cities) that will load the corresponding content in Frame 3.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Frame 2 - Links</title>
</head>
<body>
<h2>Choose a category:</h2>
<ul>
<li><a href="fruits.html" target="frame3">Fruits</a></li>
<li><a href="flowers.html" target="frame3">Flowers</a></li>
<li><a href="cities.html" target="frame3">Cities</a></li>
</ul>
</body>
</html>

Contents of default.html (Initial content for Frame 3):

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Welcome</title>
</head>
<body>
<h1>Welcome to the Info Page</h1>
<p>Select a category from the left to view more information.</p>
</body>
</html>

Contents of fruits.html (Content for Fruits):


<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Fruits</title>
</head>
<body>
<h1>Fruits</h1>
<p>Here is some information about various fruits.</p>
</body>
</html>

Contents of flowers.html (Content for Flowers):

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Flowers</title>
</head>
<body>
<h1>Flowers</h1>
<p>Here is some information about various flowers.</p>
</body>
</html>

Contents of cities.html (Content for Cities):


<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Cities</title>
</head>
<body>
<h1>Cities</h1>
<p>Here is some information about various cities.</p>
</body>
</html>

41) Write a JavaScript program that will display list of student in ascending order according to the marks & calculate the average
performance of the class.

<html>
<body>
<script>
var students = [["Amit", 70],["Sumit", 78],["Abhishek", 71],];
var Avgmarks = 0;
for (var i = 0; i < students.length; i++) {
Avgmarks += students[i][1];
for (var j = i + 1; j < students.length; j++) {
if (students[i] > students[j]) {
a = students[i];
students[i] = students[j];
students[j] = a
}
}
}
var avg = Avgmarks / students.length;
document.write("Average grade: " + Avgmarks / students.length);
document.write("<br><br>");
for (i = 0; i < students.length; ++i){
document.write(students[i]+"<br>")
}
</script>
</body>
</html>

42) Write HTML script that will display following structure

Write the JavaScript code for below operations :


(1) Name, Email & Pin Code should not be blank.
(2) Pin Code must contain 6 digits & it should not be accept any characters.

<html>
<head>
<style>
table,tr,td
{
border: solid black 1px;
border-collapse: collapse;
}
td
{
padding: 10px;
}
</style>
</head>
<body>
<table>
<tbody>
<tr>
<td>Name : </td>
<td> <input type="text" id="name" required></td>
</tr>
<tr>
<td>Email : </td>
<td> <input type="email" id="email" required></td>
</tr>
<tr>
<td>Pin code : </td>
<td> <input type="number" id="pin" required></td>
</tr>
<tr>
<td></td>
<td><button onclick="submit()">Submit</button></td>
</tr>
</tbody>
</table>
</body>
<script>
function submit()
{
var name = document.getElementById("name").value;
var email = document.getElementById("email").value;
var pin = Number(document.getElementById("pin").value);
if(name.length==0 || email.length==0 || pin.length==0)
{
alert("Please enter value in all fields.")
}
else
{
var pinpattern =/^[4]{1}[0-9]{5}$/;
if( pinpattern.test(pin))
{
alert("Perfect Pin code");
}
else
{
alert("Wrong Pin code.");
}
}
}
</script>
</html>

43) Write a JavaScript for creating following frame structure :

Chapter 1 & Chapter 2 are linked to the webpage Ch1 HTML & Ch2.html respectively. When user click on these links
corresponding data appears in FRAME3.

Step 1) create file frame1.html


<html>
<body>
<h1 align="center">FRAME1</h1>
</body>
</html>
Step 2) create frame2.html
<html>
<head>
<title>FRAME 2</title>
</head>
<body><H1>Operating System</H1>
<a href="Ch1.html" target="c"><UL>Chapter 1</UL></a>
<br>
<a href=" Ch2.html" target="c"><UL> Chapter 2</UL></a>
</body>
</html>
Step 3) create frame3.html
<html>
<body>
<h1>FRAME3</h1>
</body>
</html>
Step4) create frame_target.html
<html>
<head>
<title>Create a Frame</title>
</head>
<frameset rows="30%,*" border="1">
<frame src="frame1.html" name="a" />
<frameset cols="50%,*" border="1">
<frame src="frame2.html" name="b" />
<frame src="frame3.html" name="c" />
</frameset>
</frameset>
</html>

Output::

You might also like