QB - CSS PR Exam 2024 P16
QB - CSS PR Exam 2024 P16
<!DOCTYPE html>
<html>
<body>
<h1>Employee Details</h1>
<label>Name: </label>
<input type="text" id="name" placeholder="Enter Name"><br><br>
<label>Age: </label>
<input type="number" id="age" placeholder="Enter Age"><br><br>
<label>Salary: </label>
<input type="number" id="salary" placeholder="Enter
Salary"><br><br>
<label>Department: </label>
<input type="text" id="dept" placeholder="Enter
Department"><br><br>
<button onclick="showEmployee()">Submit</button>
<h2>Employee Details:</h2>
<p id="output"></p>
<script>
const employee = {
emp_name: "",
emp_age: 0,
salary: 0,
dept: "",
function showEmployee() {
employee.name = document.getElementById("name").value;
employee.age = document.getElementById("age").value;
employee.employeeSalary =
document.getElementById("salary").value;
employee.department = document.getElementById("dept").value;
document.getElementById("output").innerHTML = `
Name: ${employee.name}<br>
Age: ${employee.age}<br>
Salary: ${employee.employeeSalary}<br>
Department: ${employee.department}`;
}
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<h1>Simple Calculator</h1>
<label for="operation">Choose Operation:</label>
<select id="operation">
<option value="add">Add</option>
<option value="subtract">Subtract</option>
<option value="multiply">Multiply</option>
<option value="divide">Divide</option>
<option value="square">Square</option>
<option value="cube">Cube</option>
</select>
<br>
<input type="number" id="num1" placeholder="Enter first number">
<br>
<input type="number" id="num2" placeholder="Enter second number (if
needed)">
<br>
<button onclick="calculate()">Calculate</button>
<h2 id="result">Result: </h2>
<script>
function calculate() {
const operation = document.getElementById("operation").value;
const num1 = parseFloat(document.getElementById("num1").value);
const num2 = parseFloat(document.getElementById("num2").value);
let result;
switch (operation) {
case "add":
result = num1 + num2;
break;
case "subtract":
result = num1 - num2;
break;
case "multiply":
result = num1 * num2;
break;
case "divide":
if (num2 !== 0) {
result = num1 / num2;
} else {
result = "Division by zero is not allowed!";
}
break;
case "square":
result = num1 ** 2;
break;
case "cube":
result = num1 ** 3;
break;
default:
result = "Invalid operation!";
}
5 Write a program to use window object methods such as alert, prompt and
confirm.
<!DOCTYPE html>
<html>
<body>
<h1>Window Object Methods Example</h1>
<button onclick="useWindowMethods()">Click Me</button>
<script>
function useWindowMethods() {
alert("Welcome to the Window Object Methods Demo!");
const name = prompt("What is your name?");
if (name) {
if (confirm(`Your name is ${name}. Is that correct?`)) {
alert(`Nice to meet you, ${name}!`);
} else {
alert("Please try again!");
}
} else {
alert("You didn't enter your name!");
}
}
</script>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<body>
<h1>Array Sorting</h1>
<button onclick="createArray()">Enter Array Elements</button>
<div id="table-container"></div>
<script>
function createArray() {
const input = prompt("Enter numbers separated by commas:");
if (!input) {
alert("No input provided!");
return;
}
if (arr.some(isNaN)) {
alert("Please enter valid numbers!");
return;
}
document.getElementById("table-container").innerHTML = `
<table border="1" style="margin-top: 20px;
border-collapse: collapse; width: 50%; text-align: center;">
<tr><th>Original</th>
<th>Ascending</th>
<th>Descending</th></tr>
<tr>
<td>${arr.join(", ")}</td>
<td>${ascending.join(", ")}</td>
<td>${descending.join(", ")}</td>
</tr>
</table>`;
}
</script>
</body>
</html>
7 Write a Java Script to Demonstrate the use of Functions used with array.
<!DOCTYPE html>
<html lang="en">
<head>
<script>
function arrayFunctions() {
let numbers = [1, 2, 3, 4, 5];
let squares = numbers.map(num => num * num);
document.getElementById("squares").innerHTML = "Squared
Numbers: " + squares.join(", ");
let evenNumbers = numbers.filter(num => num % 2 === 0);
document.getElementById("evenNumbers").innerHTML = "Even
Numbers: " + evenNumbers.join(", ");
let sum = numbers.reduce((total, num) => total + num, 0);
document.getElementById("sum").innerHTML = "Sum of
Numbers: " + sum;
}
</script>
</head>
<body>
<h1>Array Functions Example</h1>
<button onclick="arrayFunctions()">Click to Run Functions</button>
<p id="squares"></p>
<p id="evenNumbers"></p>
<p id="sum"></p>
</body>
</html>
Write a Java Script to take name and age from user and pass it as an
8 argument to a function and display that the user is eligible for voting or
not.
<!DOCTYPE html>
<html lang="en">
<head>
<script>
function checkEligibility(name, age) {
if (age >= 18) {
document.getElementById("result").innerText = name + " is
eligible to vote.";
} else {
document.getElementById("result").innerText = name + " is
not eligible to vote.";
}
}
function getUserInput() {
let name = document.getElementById("name").value;
let age = document.getElementById("age").value;
age = parseInt(age);
checkEligibility(name, age);
}
</script>
</head>
<body>
<h1>Check Voting Eligibility</h1>
<label for="name">Enter your Name:</label>
<input type="text" id="name" required><br><br>
<p id="result"></p>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<script>
const students = [
{ name: "Alice", marks: 75 },
{ name: "Bob", marks: 85 },
{ name: "Charlie", marks: 90 },
{ name: "David", marks: 60 },
{ name: "Eva", marks: 80 }
];
function sortStudentsByMarks() {
students.sort((a, b) => a.marks - b.marks);
displayStudents();
}
function displayStudents() {
let studentList = "";
let totalMarks = 0;
students.forEach(student => {
studentList += `${student.name}: ${student.marks}<br>`;
totalMarks += student.marks;
});
let averageMarks = totalMarks / students.length;
document.getElementById("studentList").innerHTML =
studentList;
document.getElementById("averageMarks").innerHTML =
"Average Marks: " + averageMarks.toFixed(2);
}
window.onload = sortStudentsByMarks;
</script>
</head>
<body>
<h1>Student Marks List</h1>
<button onclick="sortStudentsByMarks()">Sort by Marks</button>
<div>
<h2>Sorted Student List:</h2>
<p id="studentList"></p>
<p id="averageMarks"></p>
</div>
</body>
</html>
Write a Java Script to take String from the user. Then take the start and
12 end point for substring from the user and display the result in alert box.(
eg. hello world is entered and user gives 6 and 10 then world must be
displayed).
<!DOCTYPE html>
<html lang="en">
<head>
<script>
function getSubstring() {
let inputString = prompt("Enter a string:");
let startPoint = parseInt(prompt("Enter the start index for
substring:"));
let endPoint = parseInt(prompt("Enter the end index for
substring:"));
let substring = inputString.slice(startPoint, endPoint);
alert("The extracted substring is: " + substring);
}
</script>
</head>
<body>
<h1>Substring Extraction</h1>
<button onclick="getSubstring()">Get Substring</button>
</body>
</html>
Write a Program to take input a String from user and demonstrate the
13 difference between the split(), substring() and substr() methods of String.
<!DOCTYPE html>
<html lang="en">
<head>
<script>
function demonstrateStringMethods() {
let inputString = prompt("Enter a string:");
let splitResult = inputString.split(" ");
let splitOutput = "Result of split() method: " + splitResult.join(", ");
alert(splitOutput);
alert(substringOutput);
alert(substrOutput);
}
</script>
</head>
<body>
<h1>Demonstrating String Methods: split(), substring(), and
substr()</h1>
<button onclick="demonstrateStringMethods()">Demonstrate String
Methods</button>
</body>
</html>
Write a Java Script to create an Associative array of Fruits with its price (
14 "Fruit" : price) by taking input from the user and display only those fruits
whose price is greater than 500 in a tabular form.
<!DOCTYPE html>
<html lang="en">
<head>
<script>
function filterFruitsByPrice() {
let fruits = {};
table += "</table>";
document.getElementById("result").innerHTML = table;
}
</script>
</head>
<body>
<h1>Filter Fruits by Price</h1>
<button onclick="filterFruitsByPrice()">Enter Fruit Prices</button>
<div id="result"></div>
</body>
</html>
Write a JavaScript program for a travel booking form that collects details
16 like Traveler Name, Destination, Travel Date, and Number of Travelers.
Use a drop-down menu to allow users to select the mode of transport
(e.g., Air, Train, Bus). Depending on the selected transport mode,
dynamically update a list of available companies for booking.
<!DOCTYPE html>
<html lang="en">
<head>
<script>
function updateCompanies() {
const transportMode =
document.getElementById("transportMode").value;
const companiesDropdown =
document.getElementById("companyList");
const companies = {
"Air": ["Air India", "IndiGo", "SpiceJet", "Vistara"],
"Train": ["Indian Railways", "Shatabdi Express", "Rajdhani
Express"],
"Bus": ["VRL", "SRS Travels", "KSRTC"]
};
if (companies[transportMode]) {
companiesDropdown.innerHTML = companies[transportMode]
.map(company => `<option
value="${company}">${company}</option>`).join('');
}
else {
companiesDropdown.innerHTML = '';
}
}
function submitForm() {
const form = document.getElementById("bookingForm");
const data = new FormData(form);
const details = `
Booking Details:
Name: ${data.get('travelerName')}
Destination: ${data.get('destination')}
Travel Date: ${data.get('travelDate')}
Number of Travelers: ${data.get('numTravelers')}
Transport Mode: ${data.get('transportMode')}
Selected Company: ${data.get('companyList')}
`;
alert(details);
}
</script>
</head>
<body>
<h1>Travel Booking Form</h1>
<form id="bookingForm" onsubmit="submitForm();">
<label>Traveler Name: <input type="text" name="travelerName"
required></label><br><br>
<label>Destination: <input type="text" name="destination"
required></label><br><br>
<label>Travel Date: <input type="date" name="travelDate"
required></label><br><br>
<label>Number of Travelers: <input type="number"
name="numTravelers" min="1" required></label><br><br>
<label>Mode of Transport:
<select name="transportMode" id="transportMode"
onchange="updateCompanies()" required>
<option value="" disabled selected>Select</option>
<option value="Air">Air</option>
<option value="Train">Train</option>
<option value="Bus">Bus</option>
</select>
</label><br><br>
<label>Transport Company:
<select name="companyList" id="companyList" required>
<option value="" disabled selected>Select</option>
</select>
</label><br><br>
<button type="submit">Submit Booking</button>
</form>
</body>
</html>
Design a form with a dropdown to select a fruit (e.g., Apple, Banana) and
17 a quantity (text input). Include a button that changes the background
color based on the selected fruit and displays the chosen fruit and
quantity below the form.
<!DOCTYPE html>
<html lang="en">
<head>
<script>
function updateBackgroundAndDisplay() {
let selectedFruit = document.getElementById("fruit").value;
let quantity = document.getElementById("quantity").value;
let outputDiv = document.getElementById("output");
let color = "";
if (selectedFruit === "Apple") {
color = "lightcoral";
} else if (selectedFruit === "Banana") {
color = "lightyellow";
} else if (selectedFruit === "Orange") {
color = "lightorange";
}
document.body.style.backgroundColor = color;
<form>
<label for="fruit">Select a fruit:</label>
<select id="fruit">
<option value="Apple">Apple</option>
<option value="Banana">Banana</option>
<option value="Orange">Orange</option>
</select><br><br>
<label for="quantity">Enter quantity:</label>
<input type="text" id="quantity" placeholder="Enter
quantity"><br><br>
<button type="button"
onclick="updateBackgroundAndDisplay()">Submit</button>
</form>
<div id="output"></div>
</body>
</html>
Create a quiz form that features a question with multiple radio button
18 options (e.g., favorite hobby, favorite game, etc.) and a text input for the
user’s name. Validate that an option is selected before displaying a
summary of the inputs upon submission.
<!DOCTYPE html>
<html lang="en">
<head>
<script>
function submitQuiz() {
const name = document.getElementById("name").value;
const favoriteHobby =
document.querySelector('input[name="hobby"]:checked');
<form>
<label>Your Name: <input type="text" id="name"
required></label><br><br>
<div id="summary"></div>
</body>
</html>
Write a pet adoption form with text inputs for Applicant Name and
19 Contact Number, a dropdown for Pet Type (e.g., Dog, Cat), and a text
area for additional information. Upon submission, display the entered
details along with a message based on the selected pet type.
<!DOCTYPE html>
<html lang="en">
<head>
<script>
function submitForm() {
const name = document.getElementById("applicantName").value;
const contact =
document.getElementById("contactNumber").value;
const pet = document.getElementById("petType").value;
const info = document.getElementById("additionalInfo").value;
document.getElementById("formSummary").innerHTML =
message;
}
</script>
</head>
<body>
<form>
<label>Name: <input type="text" id="applicantName"
required></label><br><br>
<label>Contact: <input type="text" id="contactNumber"
required></label><br><br>
<label>Pet Type:
<select id="petType" required>
<option value="" disabled selected>Select a pet</option>
<option value="Dog">Dog</option>
<option value="Cat">Cat</option>
</select>
</label><br><br>
<label>Additional Info:</label><br>
<textarea id="additionalInfo" placeholder="Any additional
details..."></textarea><br><br>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<script>
function onHover() {
document.getElementById("myButton").innerText = "Hovered!";
document.body.style.backgroundColor = "#f0f8ff";
}
function onLeave() {
document.getElementById("myButton").innerText = "Click Me!";
document.body.style.backgroundColor = "white";
}
</script>
</head>
<body>
</body>
</html>
Develop a form with several input fields. Write JavaScript code that
21 changes the border color of an input field to green when it gains focus and
to red when it loses focus (blur).
<!DOCTYPE html>
<html>
<head>
<script>
const inputs = document.querySelectorAll('input');
inputs.forEach(input => {
input.addEventListener('focus', () => {
input.style.border = '2px solid green';
input.style.outline = 'none';
});
input.addEventListener('blur', () => {
input.style.border = '2px solid red';
});
});
</script>
</head>
<body>
<h1>Form with Focus and Blur Events</h1>
<form>
<label for="name">Name:</label>
<input type="text" id="name”>
<br><br>
<label for="email">Email:</l
Write a JavaScript function that listens for the keydown event on an input
22 box. When a key is pressed, log the key's value to the console.
Develop an input box that counts the number of characters entered. Write
23 JavaScript code that listens for the input event and updates a paragraph
with the character count in real-time.
<!DOCTYPE html>
<html lang="en">
<body>
<h1>Character Counter</h1>
<label for="inputBox">Type something:</label><br>
<input type="text" id="inputBox" placeholder="Start typing...">
<p id="charCount">Character Count: 0</p>
<script>
const inputBox = document.getElementById("inputBox");
const charCount = document.getElementById("charCount");
inputBox.addEventListener("input", function () {
charCount.textContent = "Character Count: " + inputBox.value.length;
});
</script>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<body>
<script>
const mouseArea = document.getElementById('mouseArea');
const eventInfo = document.getElementById('eventInfo');
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,
initial-scale=1.0">
<title>Font Style and Size Modifier</title>
</head>
<body>
<!-- Textbox where font style and size will change -->
<input type="text" id="textbox" value="Sample Text" size="30">
<br><br>
Create a web page with a set of radio buttons that allow users to select a
28 category of options (e.g., Fruits, Vegetables, or Grains). Depending on the
selected category, dynamically generate corresponding checkbox options.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,
initial-scale=1.0">
<title>Dynamic Checkbox Generation</title>
<script>
// Function to update checkboxes based on the selected category
function updateOptions() {
// Get the selected category
var category =
document.querySelector('input[name="category"]:checked').value;
var optionsContainer = document.getElementById('options');
// Clear previous options
optionsContainer.innerHTML = '';
<h2>Select a Category</h2>
</body>
</html>
Design a simple survey form using HTML and JavaScript that includes
29 two radio buttons ("Yes" and "No"), a checkbox for "Subscribe to
newsletter," and a "Submit" button. Upon clicking the "Submit" button,
display a thank you message in a read-only textarea based on the user's
selections.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,
initial-scale=1.0">
<title>Survey Form</title>
<script>
// Function to handle the form submission and display the thank you
message
function submitForm() {
// Get the value of the "Yes" or "No" radio button
var yesNoAnswer =
document.querySelector('input[name="survey"]:checked');
if (!yesNoAnswer) {
alert("Please select Yes or No.");
return;
}
<h2>Survey Form</h2>
<br><br>
<br><br>
<br><br>
</body>
</html>
Create a JavaScript program that changes the text of a label based on the
30 value of an input field as the user types. The label should update in
real-time to reflect the current input. Use an image instead of button to
implement intrensic function.
Write a JS Program to create a student registration form. Accept the
31 following details: StudentName, StudentAge, StudentPhoneNumber.
Use a drop-down menu to allow the user to select their year.
Dynamically change the item of the next drop-down menu to allow the
user to choose the semester. Use an image instead of button to
implement intrensic function.
<!DOCTYPE html>
<html lang="en">
<body>
<div class="form-container">
<h2>Student Registration</h2>
<form id="registrationForm">
<label for="studentName">Student Name:</label>
<input type="text" id="studentName" name="studentName"
required>
<label for="year">Year:</label>
<select id="year" name="year"
onchange="updateSemesterOptions()" required>
<option value="">Select Year</option>
<option value="1">First Year</option>
<option value="2">Second Year</option>
<option value="3">Third Year</option>
<option value="4">Fourth Year</option>
</select>
<label for="semester">Semester:</label>
<select id="semester" name="semester" required>
<option value="">Select Semester</option>
</select>
<br>
<img src="https://via.placeholder.com/30" alt="Submit"
onclick="submitForm()">
</form>
</div>
<script>
function updateSemesterOptions() {
const year = document.getElementById('year').value;
const semesterDropdown = document.getElementById('semester');
semesters.forEach(semester => {
const option = document.createElement("option");
option.value = semester;
option.textContent = semester;
semesterDropdown.appendChild(option);
});
}
function submitForm() {
const form = document.getElementById('registrationForm');
const studentName =
document.getElementById('studentName').value;
const studentAge = document.getElementById('studentAge').value;
const studentPhone =
document.getElementById('studentPhone').value;
const year = document.getElementById('year').value;
const semester = document.getElementById('semester').value;
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,
initial-scale=1.0">
<title>Cookie Operations</title>
<script>
// Function to create a cookie
function createCookie(name, value, days) {
let expires = "";
if (days) {
const date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000)); //
Set expiry in days
expires = "; expires=" + date.toUTCString();
}
document.cookie = name + "=" + encodeURIComponent(value) +
expires + "; path=/";
alert("Cookie created: " + name + "=" + value);
}
// Function to read a cookie
function readCookie(name) {
const nameEQ = name + "=";
const cookiesArray = document.cookie.split(';');
for (let i = 0; i < cookiesArray.length; i++) {
let cookie = cookiesArray[i].trim();
if (cookie.indexOf(nameEQ) === 0) {
return
decodeURIComponent(cookie.substring(nameEQ.length));
}
}
return null; // Return null if cookie is not found
}
// Function to delete a cookie
function deleteCookie(name) {
document.cookie = name + "=; expires=Thu, 01 Jan 1970 00:00:00
UTC; path=/";
alert("Cookie deleted: " + name);
}
// Handle button clicks to perform operations
function handleCreate() {
const name =
document.getElementById("cookieName").value.trim();
const value =
document.getElementById("cookieValue").value.trim();
const days =
parseInt(document.getElementById("cookieDays").value) || 0;
if (!name) {
alert("Please enter a cookie name.");
return;
}
createCookie(name, value, days);
}
function handleRead() {
const name =
document.getElementById("cookieName").value.trim();
if (!name) {
alert("Please enter the cookie name to read.");
return;
}
const result = readCookie(name);
if (result) {
alert("Cookie value: " + result);
} else {
alert("Cookie not found! Make sure you have created it.");
}
}
function handleDelete() {
const name =
document.getElementById("cookieName").value.trim();
if (!name) {
alert("Please enter the cookie name to delete.");
return;
}
deleteCookie(name);
}
</script>
</head>
<body>
<h1>Cookie Operations</h1>
<form onsubmit="return false;">
<label for="cookieName">Cookie Name:</label>
<input type="text" id="cookieName" placeholder="Enter cookie
name" required><br><br>
<label for="cookieValue">Cookie Value:</label>
<input type="text" id="cookieValue" placeholder="Enter cookie
value"><br><br>
<label for="cookieDays">Expiry Days:</label>
<input type="number" id="cookieDays" placeholder="Enter expiry in
days"><br><br>
<button onclick="handleCreate()">Create Cookie</button>
<button onclick="handleRead()">Read Cookie</button>
<button onclick="handleDelete()">Delete Cookie</button>
</form>
</body>
</html>
ISME COOKIE READ NHI HO RAHA HAI
Write a JS Program to implement window functions like: resizeBy,
33 resizeTo, scrollBy, scrollTo, moveBy, moveTo, open a window on the
same tab, open the window on a new tab and open a window on a new
page.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,
initial-scale=1.0">
<title>Window Functions Demo</title>
<script>
// Resize the window by the specified width and height
function resizeByExample() {
window.resizeBy(100, 100); // Increase the window by 100px in
width and height
alert("Window resized by 100px in both directions.");
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,
initial-scale=1.0">
<title>Open New Window</title>
<script>
// Function to open a new window
function openWindow() {
// URL of the new window
const url = "https://ves.ac.in/polytechnic/"; // You can change this
to any URL
// Window properties
const width = 500;
const height = 400;
const left = 100; // Position from left side of the screen
const top = 100; // Position from top of the screen
Create a function that opens three new browser windows with different
37 URLs: one for a search engine (e.g., Google), one for a social media site
(e.g., Facebook), and one for a news site (e.g., BBC). Use setTimeout to
focus each window in sequence with a delay of 3 seconds between each
focus action.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,
initial-scale=1.0">
<title>Open and Focus Windows</title>
</head>
<body>
<h1>Open and Focus Windows Example</h1>
<button onclick="openAndFocusWindows()">Open and Focus
Windows</button>
<script>
function openAndFocusWindows() {
// Open three different windows with specified URLs
let googleWindow = window.open("https://www.google.com",
"_blank");
let facebookWindow = window.open("https://www.facebook.com",
"_blank");
let bbcWindow = window.open("https://www.bbc.com", "_blank");
setTimeout(function() {
facebookWindow.focus(); // Focus on Facebook window
}, 6000);
setTimeout(function() {
bbcWindow.focus(); // Focus on BBC window
}, 9000);
}
</script>
</body>
</html>
Create a script that sets a cookie with a specific expiration date (e.g., 30
39 days from now) and displays a message indicating when the cookie will
expire.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,
initial-scale=1.0">
<title>Cookie Expiration Example</title>
</head>
<body>
<h1>Cookie Expiration Example</h1>
<p id="cookieMessage"></p>
<script>
// Function to set a cookie with a specific expiration date
function setCookie(name, value, days) {
const date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000)); //
Calculate expiration date
const expires = "expires=" + date.toUTCString(); // Format
expiration date to UTC string
document.cookie = `${name}=${value}; ${expires}; path=/`; //
Set the cookie
}
// Call the function to set the cookie and display the expiration
message
displayCookieExpirationMessage();
</script>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,
initial-scale=1.0">
<title>Open and Close Window</title>
</head>
<body>
<h1>Open and Close Window Example</h1>
<button onclick="openNewWindow()">Open New Window</button>
<script>
let newWindow = null;
function openNewWindow() {
// Open a new window
newWindow = window.open('', '_blank', 'width=400, height=300');
// Write content to the new window
newWindow.document.write(`
<h1>Welcome to the New Window</h1>
<p>This is a paragraph inside the new window.</p>
<button onclick="window.close()">Close Window</button>
`);
// Optional: You can close the window after some time if desired
(e.g., after 10 seconds)
// setTimeout(() => {
// newWindow.close();
// }, 10000);
}
</script>
</body>
</html>
Create a JavaScript application with two buttons: the first opens a window
41 displaying the current date in DD/MM/YYYY format, and the second
opens another window displaying all prime numbers between 1 and 50.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,
initial-scale=1.0">
<title>Simple App</title>
<style>
body {
font-family: Arial, sans-serif;
text-align: center;
margin-top: 50px;
}
button {
font-size: 16px;
padding: 10px 20px;
margin: 10px;
border-radius: 5px;
background-color: #4CAF50;
color: white;
cursor: pointer;
transition: background-color 0.3s;
}
button:hover {
background-color: #45a049;
}
</style>
</head>
<body>
<button onclick="showDate()">Show Current Date</button>
<button onclick="showPrimes()">Show Prime Numbers</button>
<script>
function showDate() {
const now = new Date();
const date = now.getDate() + "/" + (now.getMonth() + 1) + "/" +
now.getFullYear();
const dateWindow = window.open("", "DateWindow",
"width=200,height=100");
dateWindow.document.write("<h1 style='font-family: Arial;
text-align: center;'>Current Date</h1>");
dateWindow.document.write("<p style='text-align: center;'>" +
date + "</p>");
}
function showPrimes() {
let primes = "";
for (let i = 2; i <= 50; i++) {
let isPrime = true;
for (let j = 2; j < i; j++) {
if (i % j === 0) {
isPrime = false;
break;
}
}
if (isPrime) primes += i + " ";
}
const primesWindow = window.open("", "PrimesWindow",
"width=300,height=200");
primesWindow.document.write("<h1 style='font-family: Arial;
text-align: center;'>Prime Numbers (1-50)</h1>");
primesWindow.document.write("<p style='text-align: center;'>" +
primes + "</p>");
}
</script>
</body>
</html>
42
43 Write a javascript to create option list containing list of images and then
display images in new window as per selection.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,
initial-scale=1.0">
<title>Image Selector</title>
<style>
body {
font-family: Arial, sans-serif;
text-align: center;
margin-top: 50px;
}
select, button {
font-size: 16px;
padding: 10px;
margin: 10px;
}
button {
border: none;
border-radius: 5px;
background-color: #4CAF50;
color: white;
cursor: pointer;
}
button:hover {
background-color: #45a049;
}
</style>
</head>
<body>
<h1>Select an Image</h1>
<select id="imageSelector">
<option value="">-- Select an Image --</option>
<option value="https://via.placeholder.com/150">Image 1</option>
<option value="https://via.placeholder.com/200">Image 2</option>
<option value="https://via.placeholder.com/250">Image 3</option>
</select>
<button onclick="showImage()">Show Image</button>
<script>
function showImage() {
const imageUrl =
document.getElementById("imageSelector").value;
if (!imageUrl) {
alert("Please select an image.");
return;
}
const imageWindow = window.open("", "ImageWindow",
"width=400,height=400");
imageWindow.document.body.innerHTML = `<h1>Selected
Image</h1><img src="${imageUrl}" style="max-width:100%;">`;
}
</script>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,
initial-scale=1.0">
<title>Password Validator</title>
<style>
body {
font-family: Arial, sans-serif;
text-align: center;
margin-top: 50px;
}
input, button {
font-size: 16px;
padding: 10px;
margin: 10px;
}
button {
border: none;
border-radius: 5px;
background-color: #4CAF50;
color: white;
cursor: pointer;
}
button:hover {
background-color: #45a049;
}
.message {
font-size: 16px;
color: red;
margin-top: 10px;
}
</style>
</head>
<body>
<h1>Password Validator</h1>
<input type="password" id="password" placeholder="Enter your
password">
<button onclick="validatePassword()">Validate</button>
<p id="message" class="message"></p>
<script>
function validatePassword() {
const password = document.getElementById("password").value;
const message = document.getElementById("message");
if (strongPasswordRegex.test(password)) {
message.style.color = "green";
message.textContent = "Password is strong!";
} else {
message.style.color = "red";
message.textContent = "Password must be at least 8 characters
long, include at least one uppercase letter, one lowercase letter, one digit,
and one special character.";
}
}
</script>
</body>
</html>
Write a JS program that validates a phone number based on the following
45 criteria: it must be 10 digits long and may start with 7, 8, or 9.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,
initial-scale=1.0">
<title>Phone Number Validator</title>
<style>
body {
font-family: Arial, sans-serif;
text-align: center;
margin-top: 50px;
}
input, button {
font-size: 16px;
padding: 10px;
margin: 10px;
}
button {
border: none;
border-radius: 5px;
background-color: #4CAF50;
color: white;
cursor: pointer;
}
button:hover {
background-color: #45a049;
}
.message {
font-size: 16px;
margin-top: 10px;
}
</style>
</head>
<body>
<h1>Phone Number Validator</h1>
<input type="text" id="phoneNumber" placeholder="Enter phone
number">
<button onclick="validatePhoneNumber()">Validate</button>
<p id="message" class="message"></p>
<script>
function validatePhoneNumber() {
const phoneNumber =
document.getElementById("phoneNumber").value;
const message = document.getElementById("message");
if (phoneRegex.test(phoneNumber)) {
message.style.color = "green";
message.textContent = "Phone number is valid!";
} else {
message.style.color = "red";
message.textContent = "Invalid phone number. It must be 10
digits long and start with 7, 8, or 9.";
}
}
</script>
</body>
</html>
Write a JS program that validates a date in the format DD/MM/YYYY
46
47 Write a JavaScript program that will print even numbers from 1to 20
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,
initial-scale=1.0">
<title>Even Numbers</title>
<style>
body {
font-family: Arial, sans-serif;
background-color: #f4f4f9;
text-align: center;
margin-top: 50px;
}
h1 {
color: #4CAF50;
}
p{
font-size: 18px;
font-weight: bold;
color: #333;
}
#evenNumbers {
font-size: 20px;
color: #007BFF;
margin-top: 20px;
}
</style>
</head>
<body>
<h1>Even Numbers from 1 to 20</h1>
<p id="evenNumbers"></p>
<script>
let evenNumbers = "";
for (let i = 2; i <= 20; i += 2) {
evenNumbers += i + " ";
}
document.getElementById("evenNumbers").textContent =
evenNumbers;
</script>
</body>
</html>
Write a JS Program to create a textbox which will accept numbers,
48 decimal point up to 2 digits and positive or negative sign. Eg:
+123.22 is a valid number, but +123a.22 is invalid.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,
initial-scale=1.0">
<title>Number Validation</title>
<style>
body {
font-family: Arial, sans-serif;
text-align: center;
margin-top: 50px;
}
input, button {
font-size: 16px;
padding: 10px;
margin: 10px;
}
button {
border: none;
border-radius: 5px;
background-color: #4CAF50;
color: white;
cursor: pointer;
}
button:hover {
background-color: #45a049;
}
.message {
font-size: 16px;
margin-top: 10px;
}
</style>
</head>
<body>
<h1>Number Validator</h1>
<input type="text" id="numberInput" placeholder="Enter number
(+/-)123.45">
<button onclick="validateNumber()">Validate</button>
<p id="message" class="message"></p>
<script>
function validateNumber() {
const input = document.getElementById("numberInput").value;
const message = document.getElementById("message");
// Regular expression to match valid numbers: optional + or - sign,
digits, decimal point, and 2 digits after the decimal
const regex = /^[+-]?(\d+(\.\d{1,2})?)$/;
if (regex.test(input)) {
message.textContent = "Valid number!";
message.style.color = "green";
} else {
message.textContent = "Invalid number. Please enter a valid
number (+/-)123.45 format.";
message.style.color = "red";
}
}
</script>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,
initial-scale=1.0">
<title>Regex Matcher</title>
<style>
body {
font-family: Arial, sans-serif;
text-align: center;
margin-top: 50px;
background-color: #f4f4f9;
}
h1 {
color: #333;
}
textarea, input {
font-size: 16px;
padding: 10px;
margin: 10px;
width: 300px;
border: 1px solid #ccc;
border-radius: 5px;
}
button {
font-size: 16px;
padding: 10px 20px;
margin: 10px;
background-color: #4CAF50;
color: white;
border: none;
border-radius: 5px;
cursor: pointer;
}
button:hover {
background-color: #45a049;
}
p{
font-size: 16px;
margin-top: 20px;
color: #333;
}
</style>
</head>
<body>
<h1>Regex Matcher</h1>
<textarea id="textInput" placeholder="Enter text
here"></textarea><br>
<input type="text" id="patternInput" placeholder="Enter regex
pattern"><br>
<button onclick="matchPattern()">Search</button>
<p id="message"></p>
<script>
function matchPattern() {
const text = document.getElementById("textInput").value;
const pattern = document.getElementById("patternInput").value;
const regex = new RegExp(pattern, "gm");
const matches = text.match(regex);
document.getElementById("message").textContent = matches ?
`${matches.length} match(es) found.` : "No matches found.";
}
</script>
</body>
</html>
Write a JS Program to create a regex expression that will check the
50 number of times the vowels has been arrived in a sentence. Accept the
sentence from the user.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,
initial-scale=1.0">
<title>Vowel Counter</title>
<style>
body {
font-family: Arial, sans-serif;
text-align: center;
margin-top: 50px;
}
textarea, input {
font-size: 16px;
padding: 10px;
margin: 10px;
width: 300px;
border: 1px solid #ccc;
border-radius: 5px;
}
button {
font-size: 16px;
padding: 10px 20px;
margin: 10px;
background-color: #4CAF50;
color: white;
border: none;
border-radius: 5px;
cursor: pointer;
}
button:hover {
background-color: #45a049;
}
p{
font-size: 16px;
margin-top: 20px;
color: #333;
}
</style>
</head>
<body>
<h1>Vowel Counter</h1>
<textarea id="sentenceInput" placeholder="Enter a
sentence"></textarea><br>
<button onclick="countVowels()">Count Vowels</button>
<p id="message"></p>
<script>
function countVowels() {
const sentence =
document.getElementById("sentenceInput").value;
const regex = /[aeiouAEIOU]/g; // Regex to match vowels
(case-insensitive)
const matches = sentence.match(regex); // Find all vowel matches
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,
initial-scale=1.0">
<title>Books Information</title>
<style>
body {
font-family: Arial, sans-serif;
text-align: center;
margin-top: 50px;
}
table {
width: 50%;
margin: auto;
border-collapse: collapse;
}
th, td {
padding: 10px;
border: 1px solid #ccc;
}
th {
background-color: #f4f4f4;
}
tr:hover {
background-color: #f9f9f9;
}
.price {
color: green;
font-weight: bold;
}
</style>
</head>
<body>
<h1>Book Information</h1>
<table>
<thead>
<tr>
<th>Book Name</th>
<th>Original Price</th>
</tr>
</thead>
<tbody>
<tr>
<td>JavaScript for Beginners</td>
<td class="price" onmouseover="showDiscount(this, 200)"
onmouseout="hideDiscount(this, 250)">₹250</td>
</tr>
<tr>
<td>Learn HTML and CSS</td>
<td class="price" onmouseover="showDiscount(this, 350)"
onmouseout="hideDiscount(this, 450)">₹450</td>
</tr>
<tr>
<td>Advanced JavaScript</td>
<td class="price" onmouseover="showDiscount(this, 300)"
onmouseout="hideDiscount(this, 400)">₹400</td>
</tr>
<tr>
<td>Python Programming</td>
<td class="price" onmouseover="showDiscount(this, 400)"
onmouseout="hideDiscount(this, 500)">₹500</td>
</tr>
</tbody>
</table>
<script>
// Function to show discounted price
function showDiscount(element, discountedPrice) {
element.textContent = "₹" + discountedPrice; // Update price to
discounted price
element.style.color = "red"; // Change text color to red to indicate
discount
}
<script>
function loadContent(frameId, url) {
document.getElementById(frameId).src = url;
}
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<title>Frameset Example with iframes</title>
<style>
body {
margin: 0;
font-family: Arial, sans-serif;
}
#header {
height: 20%;
background-color: #f4f4f4;
text-align: center;
padding: 10px;
}
#container {
display: flex;
height: 80%;
}
#nav {
width: 30%;
background-color: #e8e8e8;
padding: 10px;
overflow-y: auto;
}
#content {
width: 70%;
}
iframe {
width: 100%;
height: 100%;
border: none;
}
a{
text-decoration: none;
color: blue;
}
a:hover {
text-decoration: underline;
}
</style>
</head>
<body>
<!-- Frame 1 -->
<div id="header">
<h1>Welcome to the Frameset Example</h1>
</div>
html
Copy code
<!DOCTYPE html>
<html>
<head>
<title>Header</title>
</head>
<body>
<h1>Welcome to the Frameset Example</h1>
</body>
</html>
html
Copy code
<!DOCTYPE html>
<html>
<head>
<title>Links</title>
</head>
<body>
<h2>Navigation Links</h2>
<ul>
<li><a href="page1.html"
target="frame3">Page 1</a></li>
<li><a href="page2.html"
target="frame3">Page 2</a></li>
<li><a href="page3.html"
target="frame3">Page 3</a></li>
</ul>
</body>
</html>
html
Copy code
<!DOCTYPE html>
<html>
<head>
<title>Default Page</title>
</head>
<body>
<h2>Welcome to the content area</h2>
<p>Select a link from the navigation to view
the content.</p>
</body>
</html>
Each page contains specific content displayed when its link is clicked.
page1.html
html
Copy code
<!DOCTYPE html>
<html>
<head>
<title>Page 1</title>
</head>
<body>
<h2>Page 1 Content</h2>
<p>This is the content of Page 1.</p>
</body>
</html>
page2.html
html
Copy code
<!DOCTYPE html>
<html>
<head>
<title>Page 2</title>
</head>
<body>
<h2>Page 2 Content</h2>
<p>This is the content of Page 2.</p>
</body>
</html>
page3.html
html
Copy code
<!DOCTYPE html>
<html>
<head>
<title>Page 3</title>
</head>
<body>
<h2>Page 3 Content</h2>
<p>This is the content of Page 3.</p>
</body>
</html>
58 Write a Java Script to demonstrate the use of Chain select menu.
<!DOCTYPE html>
<html>
<head>
<title>Simple Chain Select Menu with CSS</title>
<style>
body {
font-family: Arial, sans-serif;
margin: 20px;
background-color: #f4f4f9;
}
h2 {
text-align: center;
color: #333;
}
label {
font-size: 16px;
color: #555;
margin-right: 10px;
}
select {
padding: 8px;
font-size: 16px;
width: 200px;
margin: 10px 0;
border: 1px solid #ccc;
border-radius: 5px;
background-color: #fff;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}
select:focus {
border-color: #007BFF;
outline: none;
}
.container {
display: flex;
justify-content: center;
align-items: center;
flex-direction: column;
}
.select-wrapper {
margin: 20px;
padding: 10px;
background-color: #fff;
border-radius: 8px;
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}
.select-wrapper label {
display: block;
margin-bottom: 8px;
}
</style>
<script>
function updateSubcategory() {
const subcategoryOptions =
document.querySelectorAll("#subcategory option");
const selectedCategory =
document.getElementById("category").value;
// Show relevant subcategories, hide others
subcategoryOptions.forEach(option => {
option.style.display = option.dataset.category ===
selectedCategory ? "block" : "none";
});
// Reset subcategory selection
document.getElementById("subcategory").value = "";
}
</script>
</head>
<body>
<div class="container">
<h2>Simple Chain Select Menu</h2>
<div class="select-wrapper">
<label for="category">Category:</label>
<select id="category" onchange="updateSubcategory()">
<option value="">Select Category</option>
<option value="Fruits">Fruits</option>
<option value="Vegetables">Vegetables</option>
<option value="Animals">Animals</option>
</select>
</div>
<div class="select-wrapper">
<label for="subcategory">Subcategory:</label>
<select id="subcategory">
<option value="">Select Subcategory</option>
<option data-category="Fruits" value="Apple">Apple</option>
<option data-category="Fruits"
value="Banana">Banana</option>
<option data-category="Fruits"
value="Orange">Orange</option>
<option data-category="Vegetables"
value="Carrot">Carrot</option>
<option data-category="Vegetables"
value="Broccoli">Broccoli</option>
<option data-category="Vegetables"
value="Spinach">Spinach</option>
<option data-category="Animals" value="Dog">Dog</option>
<option data-category="Animals" value="Cat">Cat</option>
<option data-category="Animals"
value="Elephant">Elephant</option>
</select>
</div>
</div>
</body>
</html>
Write a JS Program to implement Tree Menu. Show the directory
59 structure of the folder where your CSS codes for Semester 5 are saved.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,
initial-scale=1.0">
<title>Tree Menu Example</title>
</head>
<body>
<h1>Directory Structure for Semester 5 CSS Codes</h1>
<ul id="treeMenu">
<li><span onclick="toggleVisibility('semester5')">+ Semester
5</span>
<ul id="semester5" style="display:none;">
<li><span onclick="toggleVisibility('cssFolder')">+
CSS</span>
<ul id="cssFolder" style="display:none;">
<li>styles.css</li>
<li>layout.css</li>
<li><span onclick="toggleVisibility('themesFolder')">+
themes</span>
<ul id="themesFolder" style="display:none;">
<li>dark.css</li>
<li>light.css</li>
</ul>
</li>
</ul>
</li>
<li><span onclick="toggleVisibility('imagesFolder')">+
images</span>
<ul id="imagesFolder" style="display:none;">
<li>logo.png</li>
<li>header.png</li>
</ul>
</li>
</ul>
</li>
</ul>
<script>
// Function to toggle visibility of nested folders/files
function toggleVisibility(id) {
const folder = document.getElementById(id);
const icon = event.target; // Get the clicked span element
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,
initial-scale=1.0">
<title>Dynamic Dropdown Menus</title>
</head>
<body>
<h1>Dynamic Pulldown Menus</h1>
<br><br>
<script>
// Function to update the second dropdown menu based on the first
menu selection
function updateSecondMenu() {
// Get the value of the first dropdown (category selected)
const category = document.getElementById("firstMenu").value;
const secondMenu = document.getElementById("secondMenu");
<!DOCTYPE html>
<html>
<head>
<title>Slideshow</title>
<script>
var pics = ['1.jpg', '2.jpg', '3.jpg']; // Corrected array syntax
var count = 0;
function slideshow(status) {
count = count + status;
if (count >= pics.length) { // Corrected 'lenght' to 'length'
count = 0; // Loop back to the first image
}
if (count < 0) {
count = pics.length - 1; // Loop back to the last image
}
document.img1.src = pics[count]; // Update the image source
}
</script>
</head>
<body>
<img src="1.jpg" width="200" name="img1" id="img1">
<br>
<input type="button" value="Next" onclick="slideshow(1)">
<input type="button" value="Back" onclick="slideshow(-1)">
</body>
</html>