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

CSS Practical Answers

Uploaded by

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

CSS Practical Answers

Uploaded by

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

CSS Practical answers

Practical 1

Q1 Write simple JavaScript with HTML for arithmetic expression evaluation


and message printing.

Ans.
<html>

<body>
<script language="javascript" type="text/javascript">1
function calculate() {
// Get input values
var num1 = parseFloat(document.getElementById('num1').value);
var num2 = parseFloat(document.getElementById('num2').value);
var operation = document.getElementById('operation').value;
var result = 0;

// Simple logic for arithmetic operation


if (operation === '+') {
result = num1 + num2;
} else if (operation === '-') {
result = num1 - num2;
} else if (operation === '*') {
result = num1 * num2;
} else if (operation === '/') {
result = num1 / num2;
}

// Print result and message


document.getElementById('result').innerHTML = "Result: " + result;
document.getElementById('message').innerHTML = "Evaluation completed
successfully!";
}
</script>
<body>
<h2>Simple Arithmetic Expression Evaluation</h2>
<label>First Number: </label>
<input type="number" id="num1"><br><br>
<label>Second Number: </label>
<input type="number" id="num2"><br><br>
<label>Operation (+, -, *, /): </label>
<input type="text" id="operation"><br><br>

<button onclick="calculate()">Evaluate</button>
<p id="result"></p>
<p id="message"></p>
</body>
</html>

Output: -

Q2 Explain any two features of JavaScript.

Ans. Two Features of JavaScript

1. Dynamic Typing: JavaScript is a dynamically typed language,


meaning you don’t have to specify the data type of a variable when
declaring it. Variables can change their data type at runtime. For
example, a variable can hold a number and then later be assigned a
string without any type of declaration.
2. First-Class Functions: In JavaScript, functions are treated as first-
class citizens, which means they can be stored in variables, passed as
arguments to other functions, and returned from other functions. This
feature is useful for creating higher-order functions, callbacks, and
functional programming patterns.
Q3 Explain six types of Values in JavaScript

Ans. Six Types of Values in JavaScript

1. Numbers: JavaScript uses a single type for all numbers, whether they
are integers or floating-point numbers.
2. Strings: A sequence of characters used to represent text, enclosed in
single quotes, double quotes, or backticks for template literals.
3. Booleans: Represents logical values that can only be either true or
false.
4. Null: A special value representing the intentional absence of any
object value.
5. Undefined: A value automatically assigned to variables that have
been declared but not initialized or to missing properties of an object.
6. Objects: A collection of properties, where each property is a key-value
pair. Objects can represent more complex data types, such as arrays,
functions, or even other objects.

Practical 2

Q1 1. Write a JavaScript that Displays a table as per Follows

Ans. <html>
<head>
<style>
table {
width: 200px;
border-collapse: collapse;
margin-top: 20px;
}
table,
th,
td {
border: 1px solid black;
}
th,
td {
padding: 10px;
text-align: center;
}
</style>
</head>
<body>
<table>
<thead>
<tr>
<th>Number</th>
<th>Square</th>
<th>Cube</th>
</tr>
</thead>
<tbody id="tableBody">
</tbody>
</table>
<script language="javascript" type="text/javascript">
function createTable() {
let tableBody = document.getElementById('tableBody');
for (let i = 1; i <= 10; i++) {
let row = document.createElement('tr');
row.innerHTML = `<td>${i}</td><td>${i * i}</td><td>${i * i *
i}</td>`;
tableBody.appendChild(row);
}
}
createTable();
</script>
</body>
</html>

Q2 Develop a JavaScript to generate ‘ARMSTRONG NUMBERS’ between the


range 1 to 100. [Eg: 153 is an Armstrong Number, since sum of the cube of
the digits is equal to the number i.e. [13+53+33=153]
Ans. <html>
<body>
<script language="javascript" type="text/javascript">
function findArmstrongNumbers() {
for (let num = 1; num <= 100; num++) {
let sum = 0;
let temp = num;
// Calculate the sum of the cubes of digits
while (temp > 0) {
let digit = temp % 10;
sum += digit * digit * digit;
temp = Math.floor(temp / 10);
}
// Check if sum equals the original number (Armstrong condition)
if (sum === num) {
console.log(num); // Output Armstrong number to console
}
}
}
// Call the function
findArmstrongNumbers();
</script>
</body>
</html>

Output: -

Q3 Develop a JavaScript to find prime numbers between the range 1 to 50.

Ans. <html>
<body>
<script language="javascript" type="text/javascript">
function isPrime(num) {
for (let i = 2; i <= Math.sqrt(num); i++) {
if (num % i === 0) {
return false;
}
}
return num > 1;
}
function printPrimeNumbers(n) {
for (let i = 2; i <= 50; i++) {
if (isPrime(i)) {
console.log(i);
}
}
}
printPrimeNumbers(100);
</script>
</body>
</html>

Output: -

11

13

17

19

23

29

31

37

41

43

47

Practical 3

Q1 Write short note – object as associative array in JavaScript

Ans. Associative arrays are dynamic objects that the user redefines as
needed. When you assign values to keys in a variable of type Array, the
array is transformed into an object, and it loses the attributes and methods
of Array. The length attribute has no effect because the variable is no longer
of the Array type.

Q2 Write a JavaScript Code to create and print an element in Array.

Ans. <html>
<body>
<p id="demo"></p>
<script language="javascript" type="text/javascript">
const cars = ["Tata", "Volvo", "BMW"];
document.getElementById("demo").innerHTML = cars;
</script>
</body>
</html>

Output: -

Q3 Write a JavaScript Code to implement the following methods in an Array.


push (), pop (), unshift (), sort (), reverse (), splice ()

Ans. <html>
<body>
<script language="javascript" type="text/javascript">
// Initial array
let fruits = ['Banana', 'Orange', 'Apple', 'Mango'];
console.log('Initial Array:', fruits);

// 1. push() - Adds an element to the end of the array


fruits.push('Pineapple');
console.log('After push():', fruits); // ["Banana", "Orange", "Apple",
"Mango", "Pineapple"]

// 2. pop() - Removes the last element from the array


let lastFruit = fruits.pop();
console.log('After pop():', fruits); // ["Banana", "Orange", "Apple",
"Mango"]
console.log('Removed Fruit:', lastFruit); // "Pineapple"

// 3. unshift() - Adds an element to the beginning of the array


fruits.unshift('Strawberry');
console.log('After unshift():', fruits); // ["Strawberry", "Banana",
"Orange", "Apple", "Mango"]
// 4. sort() - Sorts the array elements in place
fruits.sort();
console.log('After sort():', fruits); // Sorted array

0..

// 5. reverse() - Reverses the order of the elements in the array


fruits.reverse();
console.log('After reverse():', fruits); // Reversed array

// 6. splice() - Adds/removes elements from the array


// Remove 1 element from index 2 (Apple)
let removedFruits = fruits.splice(2, 1);
console.log('After splice():', fruits); // Array after removal
console.log('Removed Fruits:', removedFruits); // Fruits that were removed
</script>
</script>
</body>
</html>

Output: -

Initial Array:

["Strawberry", "Orange", "Banana", "Apple"]

After push():

["Strawberry", "Orange", "Banana", "Apple"]

After pop():

["Strawberry", "Orange", "Banana", "Apple"]

Removed Fruit:

Pineapple

After unshift():

["Strawberry", "Orange", "Banana", "Apple"]

After sort():
["Strawberry", "Orange", "Banana", "Apple"]

After reverse():

["Strawberry", "Orange", "Banana", "Apple"]

After splice():

["Strawberry", "Orange", "Banana", "Apple"]

Removed Fruits:

["Mango"]

Practical 4

Q1 Explain the scope of variable with the help of programming example.0.

Ans. In JavaScript, variable scope refers to the accessibility of variables in


different parts of the code. There are mainly two types of scopes:

1. Global Scope: Variables declared outside of any function or block


have global scope. They can be accessed from anywhere in the code.
2. Local Scope: Variables declared inside a function or block (like if,
for, etc.) are local to that block or function. They can't be accessed
from outside the block or function.
3. Function Scope: Variables declared inside a function are only
accessible within that function.
4. Block Scope: Variables declared with let or const inside a block
(e.g., if, for) are only accessible within that block.

Program: - 0
<html>

<body>
<script language="javascript" type="text/javascript">
// Global scope
var globalVar = "I am a global variable";

function exampleFunction() {
// Function (local) scope
var localVar = "I am a local variable";
console.log(globalVar); // Accessible (from global scope)
console.log(localVar); // Accessible (within function)

// Block scope with let/const


if (true) {
let blockScopedVar = "I am block scoped";
console.log(blockScopedVar); // Accessible (within block)
}
// console.log(blockScopedVar); // Error: blockScopedVar is not defined
}

exampleFunction();

console.log(globalVar); // Accessible (global scope)


// console.log(localVar); // Error: localVar is not defined (function scope)
</script>
</script>
</body>
</html>

Output: -

I am a global variable

I am a local variable

I am block scoped

I am a global variable

Uncaught ReferenceError: localVar is not defined

Q2 Explain the method of calling a function from HTML.

Ans. You can call a JavaScript function directly from an HTML element using
an inline event handler like onclick, onmouseover, onload, etc.

Example: Calling a Function with onclick


<html>
<body>
<button onclick="showMessage()">Click Me</button>
<script language="javascript" type="text/javascript">
function showMessage() {
alert("Button clicked! This is a function call.");
}
</script>
</body>
</html>

Q3 Write a JavaScript code to return a value from function.

Ans. <html>
<body>
<p id="demo"></p>
<script language="javascript" type="text/javascript">
function myFunction() {
return Math.PI;
}
document.getElementById("demo").innerHTML = myFunction();
</script>
</body>
</html>

Output: -

3.141592653589793

Q4 Write a JavaScript code to demonstrate function calling with arguments.

Ans. <html>
<body>
<script language="javascript" type="text/javascript">
// JavaScript function with two arguments
function addNumbers(num1, num2) {
var sum = num1 + num2;
console.log("The sum of " + num1 + " and " + num2 + " is: " + sum);
}

// Function to subtract numbers


function subtractNumbers(num1, num2) {
var difference = num1 - num2;
console.log("The difference between " + num1 + " and " + num2 + " is:
" + difference);
}

// Calling the function with different arguments


addNumbers(10, 20); // Passing 10 and 20 as arguments
subtractNumbers(50, 25); // Passing 50 and 25 as arguments
</script>
</body>
</html>

Output: -

The sum of 10 and 20 is: 30

The difference between 50 and 25 is: 25

Practical 5

Q1 Write a JavaScript code to retrieve the position of given character from


string

Ans. <html>
<body>
<script language="javascript" type="text/javascript">
// Function to find the position of a character in a string
function findCharacterPosition(string, character) {
var position = string.indexOf(character);
if (position !== -1) {
console.log("The character '" + character + "' is at position: " +
position);0
} else {
console.log("The character '" + character + "' is not found in the
string.");
}
}

// Example usage
var myString = "Hello, World!";
var characterToFind = "W";
findCharacterPosition(myString, characterToFind);
</script>
</body>
</html>

Output: - The character 'W' is at position: 7


Q2 Write a JavaScript code for implementation of following string methods.
Search(), split(), substring(), substr().

Ans. <html>

<body>
<script language="javascript" type="text/javascript">
// Example strings
const exampleString = "Hello, welcome to the world of JavaScript!";

// 1. Implementation of search() method


function customSearch(str, regex) {
return str.search(regex);
}

// 2. Implementation of split() method


function customSplit(str, separator) {
return str.split(separator);
}

// 3. Implementation of substring() method


function customSubstring(str, start, end) {
return str.substring(start, end);
}

// 4. Implementation of substr() method


function customSubstr(str, start, length) {
return str.substr(start, length);
}

// Usage
const searchResult = customSearch(exampleString, /welcome/);
console.log('Search Result:', searchResult); // Outputs the index of the
match

const splitResult = customSplit(exampleString, ' ');


console.log('Split Result:', splitResult); // Outputs an array of words

const substringResult = customSubstring(exampleString, 7, 14);


console.log('Substring Result:', substringResult); // Outputs 'welcome'

const substrResult = customSubstr(exampleString, 7, 7);


console.log('Substr Result:', substrResult); // Outputs 'welcome'
</script>
</body>
</html>

Output: -

 Split Result:

["Hello,", "welcome", "to", "the", "world", "of", "JavaScript!"]

0: "Hello,"

1: "welcome"

2: "to"

3: "the"

4: "world"

5: "of"

6: "JavaScript!"

 Substring Result:

welcome

 Substr Result:

welcome

Q3 Explain charCodeAt() and fromCharCode() method with Example.

Ans. 1. charCodeAt() Method

The charCodeAt() method returns the Unicode value (character code) of a


character at a specified index in a string. The Unicode value is an integer
representation of the character.

Syntax:

string.charCodeAt(index);

 index: The position of the character in the string whose Unicode value
you want to retrieve. Indexing starts from 0.
Example: -
<html>

<body>
<script language="javascript" type="text/javascript">
var myString = "Hello";
var code = myString.charCodeAt(1); // Get the Unicode of the character at
index 1 (which is 'e')
console.log("The Unicode value of 'e' is: " + code);
</script>
</body>

</html>

Output: -

The Unicode value of 'e' is: 101

Explanation:

 myString.charCodeAt(1) returns 101, which is the Unicode value of


the character 'e' in the string "Hello".

2. fromCharCode() Method

The fromCharCode() method converts Unicode values (character codes) into


characters. It returns a string created by using the specified sequence of
Unicode values.

Syntax:

String.fromCharCode(num1, num2, ...);

 num1, num2, ...: These are the Unicode values you want to convert
to characters.

Example: -
<html>

<body>
<script language="javascript" type="text/javascript">
var char1 = String.fromCharCode(72); // Unicode for 'H'
var char2 = String.fromCharCode(101); // Unicode for 'e'
var char3 = String.fromCharCode(108); // Unicode for 'l'
var char4 = String.fromCharCode(108); // Unicode for 'l'
var char5 = String.fromCharCode(111); // Unicode for 'o'

var myString = char1 + char2 + char3 + char4 + char5;


console.log("The string is: " + myString);
</script>
</body>

</html>

Output: -

The string is: Hello

Explanation:

 String.fromCharCode(72, 101, 108, 108, 111) converts the


Unicode values for 'H', 'e', 'l', 'l', and 'o' into their respective
characters, forming the string "Hello".

Practical 6

Q1 Explain Building blocks of form (Bhot bada hai ans appne hisab se cut kar
ke likhna )

Ans. Forms in HTML are used to collect user inputs and send them to a server
for processing. They are essential building blocks in creating interactive
websites. Below are the key building blocks (elements) of an HTML form,
along with brief descriptions:

1. <form> Element

The <form> element is the container for all input elements that make up the
form. It defines how the data will be sent and where the data will be sent to.
Key Attributes:

 action: Specifies where to send the form data (usually a URL).


 method: Defines how the data will be sent (usually GET or POST).
 enctype: Specifies how the form data should be encoded when
submitting (used with POST method for file uploads).
Example:

<form action="/submit" method="post">

<!-- Form elements go here -->

</form>

2. <input> Element

The <input> element is used to collect user input. The type of input is
controlled by the type attribute, and there are many types of inputs, such as
text, password, email, etc.

Common Types of Input:

 text: Single-line text input.


 password: Masked text input for sensitive information (e.g.,
passwords).
 email: Input for email addresses (with basic validation).
 number: Input for numeric values.
 checkbox: Allows users to select one or more options.
 radio: Allows users to select only one option from a group.
 submit: Button to submit the form.
 button: A clickable button (usually used for custom JS logic).
 file: Input to upload a file.

Example:

<input type="text" name="username" placeholder="Enter your name">

<input type="password" name="password" placeholder="Enter your


password">

<input type="submit" value="Submit">


3. <textarea> Element

The <textarea> element is used for multi-line text input. Unlike <input>,
which is generally for short inputs, <textarea> is ideal for longer texts like
comments or descriptions.

Example:

<textarea name="comments" rows="5" cols="30" placeholder="Enter your


comments"></textarea>

4. <select> Element

The <select> element creates a drop-down list. Each item in the list is
defined using the <option> element.

Example:

<select name="country">

<option value="india">India</option>

<option value="usa">USA</option>

<option value="canada">Canada</option>

</select>

5. <label> Element

The <label> element provides a clickable label for form controls. Using
labels improves the accessibility of forms, especially for screen readers. It
can be associated with an input using the for attribute or by wrapping the
input inside the label.

Example:

<label for="email">Email:</label>

<input type="email" id="email" name="email" placeholder="Enter your


email">
6. <button> Element

The <button> element is used to create clickable buttons. Unlike the <input
type="submit"> element, buttons can contain other elements like images
and allow for more customization.

Example:

<button type="submit">Submit Form</button>

7. <fieldset> and <legend> Elements

The <fieldset> element is used to group related form elements together.


The <legend> element provides a caption or title for the grouped elements.

Example:

<fieldset>

<legend>Personal Information</legend>

<label for="name">Name:</label>

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

</fieldset>

Putting It All Together:


<html>

<body>
<form action="/submit" method="post">
<fieldset>
<legend>Personal Information</legend>

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

<label for="email">Email:</label>
<input type="email" id="email" name="email" required><br>

<label for="country">Country:</label>
<select id="country" name="country">
<option value="india">India</option>
<option value="usa">USA</option>
<option value="canada">Canada</option>
</select><br>

<label for="comments">Comments:</label><br>
<textarea id="comments" name="comments" rows="5"
cols="30"></textarea><br>

<input type="submit" value="Submit">

</fieldset>
</form>
</body>
</html>

Output: -

The building blocks of an HTML form consist of elements like <form>,


<input>, <textarea>, <select>, <button>, and more, which together
enable the creation of interactive and dynamic user inputs.

Q2 Generate college Admission form using html form tag

Ans. <html>

<body>
<form action="/submit" method="post">
<!-- Personal Details -->
<fieldset>
<legend>Personal Details</legend>

<label for="firstname">First Name:</label>


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

<label for="lastname">Last Name:</label>


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

<label for="dob">Date of Birth:</label>


<input type="date" id="dob" name="dob" required>

<label for="gender">Gender:</label>
<select id="gender" name="gender">
<option value="male">Male</option>
<option value="female">Female</option>
<option value="other">Other</option>
</select><br><br>

<label for="email">Email Address:</label>


<input type="email" id="email" name="email" required><br><br>

<label for="phone">Phone Number:</label>


<input type="tel" id="phone" name="phone" placeholder="123-456-7890"
required><br><br>

<label for="address">Address:</label>
<textarea id="address" name="address" rows="4" required></textarea>
</fieldset>

<!-- Academic Details -->


<fieldset>
<legend>Academic Details</legend>

<label for="highschool">High School Name:</label>


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

<label for="board">Board of Education:</label>


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

<label for="percentage">Percentage/Grade:</label>
<input type="text" id="percentage" name="percentage" required><br><br>

<label for="course">Preferred Course:</label>


<select id="course" name="course" required>
<option value="engineering">Engineering</option>
<option value="medical">Medical</option>
<option value="commerce">Commerce</option>
<option value="arts">Arts</option>
</select><br><br>

<label for="extra">Extracurricular Activities:</label>


<textarea id="extra" name="extra" rows="3"></textarea>
</fieldset><br><br>

<!-- Submit Button -->


<input type="submit" class="submit-btn" value="Submit Application">

</form>
</body>
</html>

Output: -
Q3 Create a form which display output as given below

Ans. <html>
<body>
<form>
<fieldset>
<!-- Username and Last Name fields -->
<label for="username">User Name:</label>
<input type="text" id="username" name="username"><br><br>

<label for="lastname">Last Name:</label>


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

<!-- Submit and Reset buttons -->


<input type="submit" value="Submit">
<input type="reset" value="Reset"><br><br>

<!-- Gender radio buttons -->


<label>Gender:</label>
<input type="radio" id="male" name="gender" value="male" checked>
<label for="male">Male</label>

<input type="radio" id="female" name="gender" value="female">


<label for="female">Female</label>

<input type="radio" id="other" name="gender" value="other">


<label for="other">Other</label><br><br>

<!-- Preferences checkboxes -->


<input type="checkbox" id="programming" name="interest"
value="programming" checked>
<label for="programming">I Like Programming</label>

<input type="checkbox" id="theory" name="interest" value="theory">


<label for="theory">I Like Theory</label>
</fieldset>
</form>
</body>
</html>

Practical 7

Q1 Write a function that logs the current mouse position (x, y) relative to the
browser window whenever the mouse moves.

Ans.
 The logMousePosition function is called whenever the mouse moves
(mousemove event).
 event.clientX and event.clientY provide the x and y coordinates of
the mouse relative to the browser window.
 These coordinates are logged to the console each time the mouse is
moved.

Ans. <html>

<body>
<script language="javascript" type="text/javascript">
// Function to log mouse position
function logMousePosition(event) {
const x = event.clientX;
const y = event.clientY;
console.log(`Mouse Position - X: ${x}, Y: ${y}`);
}

// Event listener for mouse movement


document.addEventListener('mousemove', logMousePosition);
</script>
</body>

</html>

Output: -

Mouse Position - X: 2, Y: 60

Mouse Position - X: 3, Y: 60

Mouse Position - X: 3, Y: 61

Mouse Position - X: 2, Y: 61

Q2 How can you log the key code of a pressed key?

Ans. To log the key code of a pressed key in JavaScript, you can use the
keydown event listener and access the event.keyCode or event.which
property. In modern JavaScript, it's recommended to use event.code or
event.key for more reliable results across different browsers.
Here’s how you can log the key code of a pressed key:

<html>

<body>
<script language="javascript" type="text/javascript">
document.addEventListener('keydown', function(event) {
console.log("Key Code:", event.keyCode); // Old method (deprecated)
console.log("Key:", event.key); // Modern method (key value)
console.log("Code:", event.code); // Modern method (key code)
});

</script>
</body>

</html>

Output: -

Key Code: 65

Key: a

Code: KeyA

Practical 8

Q1 Write HTML Script that displays textboxes for accepting Name, Middle
name, Surname of the user and a Submit button. Write proper JavaScript
such that when the user clicks on submit button all textboxes must get
disabled and change the color to “RED”. and with respective labels.
Constructs the mailID as. @msbte.com and displays mail ID as message. (Ex.
If user enters Ranjeet as name and shergil as surname mail ID will be
constructed as Ranjeet.shergil@msbte.com).

Ans. <html>

<body>
<form id="userForm" onsubmit="generateEmailID(event)">
<label for="firstName">First Name:</label>
<input type="text" id="firstName" required> <br><br>
<label for="middleName">Middle Name:</label>
<input type="text" id="middleName" required><br><br>

<label for="surname">Surname:</label>
<input type="text" id="surname" required><br><br>

<button type="submit">Submit</button>
</form>

<div id="output"></div>
<script language="javascript" type="text/javascript">
function generateEmailID(event) {
event.preventDefault(); // Prevent form submission

// Retrieve input values


const firstName = document.getElementById("firstName").value;
const middleName = document.getElementById("middleName").value;
const surname = document.getElementById("surname").value;

// Generate email ID
const emailID = `${firstName}.${surname}@msbte.com`;

// Display email ID
document.getElementById("output").textContent = `Generated Email ID: $
{emailID}`;

// Disable textboxes and change text color to red


const inputs = [document.getElementById("firstName"),
document.getElementById("middleName"), document.getElementById("surname")];
inputs.forEach(input => {
input.disabled = true;
input.style.backgroundColor = "red";
});
}
</script>
</body>

</html>

Output: -
Q2 Write a JavaScript to create three radio buttons for Fruit, Flower, Color
and one option list. Based on respective radio button selection by user fruit,
flower, color names are shown in option list according to.

Ans. <html>

<body>
<h2>Select a Category:</h2>

<!-- Radio buttons for selecting category -->


<label>
<input type="radio" name="category" value="fruit"
onclick="updateOptions()"> Fruit
</label>
<label>
<input type="radio" name="category" value="flower"
onclick="updateOptions()"> Flower
</label>
<label>
<input type="radio" name="category" value="colour"
onclick="updateOptions()"> Colour
</label>

<h3>Options:</h3>
<!-- Dropdown for displaying options based on selection -->
<select id="optionsList">
<option>Select an option</option>
</select>

<script language="javascript" type="text/javascript">


// Function to update the options based on selected radio button
function updateOptions() {
const optionsList = document.getElementById("optionsList");
optionsList.innerHTML = ""; // Clear previous options
// Array of options based on selected category
const fruitOptions = ["Apple", "Banana", "Mango", "Orange"];
const flowerOptions = ["Rose", "Tulip", "Lily", "Jasmine"];
const colourOptions = ["Red", "Blue", "Green", "Yellow"];

// Get selected category


const selectedCategory =
document.querySelector('input[name="category"]:checked').value;

// Populate optionsList based on the selected category


let optionsArray;
if (selectedCategory === "fruit") {
optionsArray = fruitOptions;
} else if (selectedCategory === "flower") {
optionsArray = flowerOptions;
} else if (selectedCategory === "colour") {
optionsArray = colourOptions;
}

// Add options to the dropdown list


optionsArray.forEach(option => {
const optionElement = document.createElement("option");
optionElement.textContent = option;
optionsList.appendChild(optionElement);
});
}
</script>
</body>

</html>

Output: -
Practical 9

Q1 What is the purpose of the console.log() intrinsic function in JavaScript?

Ans. The console.log() function in JavaScript is primarily used to print


information to the browser's console. This function is incredibly useful for
debugging, tracking the flow of a program, and inspecting variables and
outputs without altering the actual webpage. It allows developers to check
values, identify errors, and understand the execution of code at various
points. Example:

const name = "John";

console.log("User name is:", name); // Logs: User name is: John

When this code is executed, the message "User name is: John" is printed
in the console, allowing the developer to verify that the name variable has the
expected value.

Q2 Can you explain the difference between parseInt() and parseFloat()


intrinsic functions in JavaScript?
Ans..

Q3 What is the purpose of the typeof operator in JavaScript, and how is it


related to intrinsic functions?

Ans. The typeof operator in JavaScript is used to determine the data type of
a given value or variable. It’s a quick way to check whether a value is a
string, number, boolean, object, function, or another data type.

Purpose of the typeof Operator

 Type Checking: typeof allows developers to check the type of a


variable or value, which is useful for debugging and validating data in
applications.
 Conditional Logic: Based on type, you can perform different actions.
For instance, if a value is an object, you may want to handle it
differently than if it’s a number or string.

Syntax

typeof variableOrValue;

Example Usage
typeof 42; // Returns "number"

typeof "hello"; // Returns "string"


typeof true; // Returns "boolean"

typeof {}; // Returns "object"

typeof undefined; // Returns "undefined"

typeof function() {}; // Returns "function"

Relation to Intrinsic Functions

Intrinsic functions like parseInt(), parseFloat() rely on data types to


function correctly. The typeof operator can help ensure that you pass
appropriate types to these functions by validating types beforehand.

Using typeof effectively helps manage how intrinsic functions operate on


different data types, ensuring consistency and preventing runtime errors.

Q4 Give examples of some commonly used intrinsic functions in JavaScript.

Ans. 1. parseInt()

 Purpose: Converts a string to an integer.


 Example: parseInt("42"); // Returns 42
parseInt("3.14"); // Returns 3 (truncates
decimals)

2. parseFloat()

 Purpose: Converts a string to a floating-point number.


 Example: parseFloat("3.14"); // Returns 3.14
parseFloat("42"); // Returns 42

3. Number()

 Purpose: Converts a value to a number.


 Example: Number("42"); // Returns 42
Number("3.14"); // Returns 3.14
Number("Hello"); // Returns NaN
4. String()

 Purpose: Converts a value to a string.


 Example: String(42); // Returns "42"
String(true); // Returns "true"

6. typeof

 Purpose: Returns the data type of a value as a string.


 Example: typeof 42; // Returns "number"
typeof "hello"; // Returns "string"

7. Array.isArray()

 Purpose: Checks if a value is an array.


 Example: Array.isArray([1, 2, 3]); // Returns true
Array.isArray("hello"); // Returns false

8. Math.max() and Math.min()

 Purpose: Returns the maximum or minimum value among given


numbers.
 Example: Math.max(1, 5, 3); // Returns 5
Math.min(1, 5, 3); // Returns 1

9. Math.random()

 Purpose: Returns a random number between 0 (inclusive) and


1 (exclusive).
 Example: Math.random(); // Returns a random number like
0.123456789

10. Date.now()

 Purpose: Returns the current timestamp in milliseconds.


 Example: Date.now(); // Returns something like
1623433055000 (milliseconds since 1970-01-01)

Q5 Write the use of return statement with example

Ans. Use of the return Statement

 Returning a Value: It allows a function to send a value back to where


it was called.
 Stopping Execution: It ends function execution immediately upon
reaching the return statement.

Syntax

function functionName(parameters) {

// Code

return value; // The function exits and returns 'value'

Example: Simple Function with return

This example demonstrates the return statement in a function that


calculates the square of a number and returns the result:

function calculateSquare(number) {

let square = number * number;

return square; // Returns the square of the number

let result = calculateSquare(6);

console.log("The square of 6 is:", result);

console.log outputs: The square of 6 is: 36.


Practical 10

Q1 Write a JavaScript program which accept cookie values from user &
display them, also add a button to delete those values

Ans. <html>
<body>
<form name="form1">
Enter Name: <input type="text" id="username" name="username" />
<input type="button" value="Create Cookie" onclick="createCookie()" />
<input type="button" value="Read Cookie" onclick="readCookie()" />
<input type="button" value="Delete Cookie" onclick="deleteCookie()" />
</form>
<p id="cookieValue"></p>
<script type="text/javascript">
// Function to create a cookie
function createCookie() {
var username = document.getElementById("username").value;
if (username) {
document.cookie = "UserName=" + encodeURIComponent(username) + ";
path=/;"; // Ensure proper encoding
alert("Cookie created: " + document.cookie); // Debugging message
} else {
alert("Please enter a username");
}
}

// Function to read/display the cookie


function readCookie() {
var allCookies = document.cookie.split('; ');
var cookieFound = false;
var output = ""; // For debugging all cookies
for (var i = 0; i < allCookies.length; i++) {
var cookiePair = allCookies[i].split('=');
output += "Cookie name: " + cookiePair[0] + ", Value: " +
decodeURIComponent(cookiePair[1]) + "\n"; // Debugging line
if (cookiePair[0] === "UserName") {
document.getElementById("cookieValue").innerText = "Value: " +
decodeURIComponent(cookiePair[1]);
cookieFound = true;
}
}
if (!cookieFound) {
document.getElementById("cookieValue").innerText = "Cookie not
found";
}
console.log(output); // Log all cookies to the console for debugging
}

// Function to delete the cookie


function deleteCookie() {
var expiryDate = new Date();
expiryDate.setMonth(expiryDate.getMonth() - 1); // Set expiration date
to past
document.cookie = "UserName=; expires=" +
expiryDate.toUTCString() + "; path=/;";
alert("Cookie Deleted");
document.getElementById("cookieValue").innerText = ""; // Clear
display area
}
</script>
</body>
</html>

Output

Practical 11
1. Explain open() method of window object with syntax & Example.

Ans. The open() method in JavaScript’s window object is used to open a new browser window or
tab or load a URL in a specified frame.

Syntax:
window.open(URL, name, specs, replace);
 URL (optional): The URL to open. Defaults to an empty page if omitted.
 name (optional): The target window name (_blank, _self, etc.) or a
unique name.
 specs (optional): A string of features/size for the new window (e.g.,
"width=500, height=500").
 replace (optional): Boolean, if true replaces the current page in the
history.

Example:

window.open("https://www.example.com", "_blank",
"width=600,height=400");

Output: -
This opens example.com in a new window/tab with specified dimensions.

2. Explain innerHTML property with syntax & Example

Ans. The innerHTML property in JavaScript is used to get or set the HTML
content inside an element. It allows you to dynamically change or insert
HTML within a specified element.

Syntax:

element.innerHTML = "new HTML content"; // to set


let content = element.innerHTML; // to get

Example:

<div id="myDiv">Hello, World!</div>

<script type=“text/javascript”>

// Access and change the content of myDiv

document.getElementById("myDiv").innerHTML = "Hello, JavaScript!";

</script>
In this example, the innerHTML of the <div> element is updated from "Hello,
World!" to "Hello, JavaScript!".

3. Describe the way to open multiple window in javascript with Example

Ans. To open multiple windows in JavaScript, you can use the window.open()
method multiple times, assigning each to a different variable so they can be
managed separately. Each call to window.open() opens a new browser
window or tab (depending on browser settings).
Syntax:

let window1 = window.open("URL1", "windowName1", "windowFeatures");

let window2 = window.open("URL2", "windowName2", "windowFeatures");

Example:

// Open two new windows

let googleWindow = window.open("https://www.google.com",


"GoogleWindow", "width=600”; “height=400");

let bingWindow = window.open("https://www.bing.com", "BingWindow",


"width=600”; “height=400");

// You can use these variables to refer to or control each window

googleWindow.focus();

bingWindow.focus();

In this example, two separate windows are opened, one for Google and one
for Bing, each with specific dimensions. The focus() method is used to bring
each window to the front.

4. Explain the use onfocus() method for window object.

Ans. The onfocus event in JavaScript is used to execute a function or piece


of code when a specific window or element (like an input field) gains focus.
When applied to the window object, onfocus triggers whenever the browser
window or tab becomes active after being inactive, such as when the user
returns to a previously minimized or switched window.

Syntax

window.onfocus = function() {

// Code to execute when window gains focus

};

Example
<html>

<body>

<h2>Welcome to the News Page!</h2>

<p>Switch to another window or tab, then return here to see the


effect.</p>

<script type="text/javascript">

window.onfocus = function() {

alert("Welcome back! Let's refresh the latest news.");

// Code to refresh content or data could go here

};

</script>

</body>

</html>

Practical 12

1. Describe Regular Expression and Methods

Ans. A regular expression (regex) is a sequence of characters used for


pattern matching within strings. It is commonly used for searching,
validating, and manipulating text. Some commonly used regex methods in
JavaScript are:

 test(): Checks if a pattern exists in a string, returning true or false.


 exec(): Searches for a match in a string and returns the matched text
or null if no match is found.
 match(): Searches a string for a match against a regular expression
and returns an array of matches or null.
 replace(): Replaces matched text in a string with a new text.
Example:

<html>
<body>
<script type="text/javascript">
let text = "Hello123";
let pattern = /\d+/;

// test() method
console.log(pattern.test(text)); // true

// exec() method
console.log(pattern.exec(text)); // ["123"]

// match() method
console.log(text.match(pattern)); // ["123"]

// replace() method
console.log(text.replace(pattern, "456")); // "Hello456"
</script>
</body>
</html>

2. Program to Find Non-Matching Characters

Ans. This program finds characters in a string that do not match a specific
pattern.

<html>
<body>
<script type="text/javascript">
let text = "abc123";
let pattern = /[^a-z]/g; // Find non-lowercase letters
let nonMatching = text.match(pattern);
console.log("Non-matching characters:", nonMatching);
</script>
</body>
</html>
Output: -

Non-matching characters: (3) ["1", "2", "3"]

3. Program to Find Non-Digit Characters

Ans. This program finds characters that are not digits in a given string.

<html>
<body>
<script type="text/javascript">
let text = "abc123";
let pattern = /\D/g; // Find non-digit characters
let nonDigits = text.match(pattern);
console.log("Non-digit characters:", nonDigits);
</script>
</body>
</html>

Output: -

Non-digit characters: (3) ["a", "b", "c"]

4. Program to Find Matching Pattern

This program checks if a pattern is present in the given text.

<html>
<body>
<script type="text/javascript">
let text = "This is an example text.";
let pattern = /example/;
let isMatch = pattern.test(text);

console.log("Pattern found:", isMatch); // true if


"example" is in text
</script>
</body>
</html>

Output: -
Pattern found: true

Practical 13

1. JavaScript to Display Fruit Image on Rollover

Ans. This JavaScript program displays the image of a fruit when the user
hovers over its name.

<html>

<body>
<h3>Hover over the fruit name to see the image:</h3>

<div onmouseover="showImage('mango')" onmouseout="hideImage()">Mango</div>


<div onmouseover="showImage('apple')" onmouseout="hideImage()">Apple</div>
<div onmouseover="showImage('banana')" onmouseout="hideImage()">Banana</div>

<img id="fruitImage" src="" alt="Fruit Image" style="display:none;


width:100px; height:100px;">

<script type="text/javascript">
function showImage(fruit) {
let image = document.getElementById("fruitImage");
image.style.display = "block";
image.src = fruit + ".jpg"; // Assuming images are named mango.jpg,
apple.jpg, banana.jpg
}

function hideImage() {
let image = document.getElementById("fruitImage");
image.style.display = "none";
}
</script>
</body>

</html>

Output: -
In this example, you’ll need images named mango.jpg, apple.jpg, and
banana.jpg in the same directory. When you hover over the fruit name, the
corresponding image will be displayed.

2. JavaScript to Display Fruit Image and Pop-Up with Benefits on Rollover

Ans. This JavaScript program not only shows the image of the fruit but also
opens an alert or pop-up window displaying the benefits of each fruit.

<html>
<body>
<h3>Hover over the fruit name to see the image and benefits:</h3>

<div onmouseover="showImageAndBenefits('mango')"
onmouseout="hideImage()">Mango</div>
<div onmouseover="showImageAndBenefits('apple')"
onmouseout="hideImage()">Apple</div>
<div onmouseover="showImageAndBenefits('banana')"
onmouseout="hideImage()">Banana</div>

<img id="fruitImage" src="" alt="Fruit Image" style="display:none; width:100px;


height:100px;">

<script type="text/javascript">
function showImageAndBenefits(fruit) {
let image = document.getElementById("fruitImage");
image.style.display = "block";
image.src = fruit + ".jpg"; // Assuming images are named mango.jpg,
apple.jpg, banana.jpg

let benefits = {
mango: "Mango is rich in vitamin C and antioxidants.",
apple: "Apple helps in digestion and boosts immunity.",
banana: "Banana provides potassium and energy."
};

alert(benefits[fruit]); // Pop-up displaying the benefit of the fruit


}

function hideImage() {
let image = document.getElementById("fruitImage");
image.style.display = "none";
}
</script>
</body>
</html>

3. Features of Rollover

Ans. Rollover effects provide visual feedback when the user interacts with an
element by hovering or "rolling over" it. Here are the main features of
rollover effects:

 Interactivity: Rollover effects make websites more interactive and


engaging for users.
 Visual Feedback: They provide immediate visual feedback, indicating
that the element is clickable or interactive.
 Enhanced User Experience: Rollovers help guide users by indicating
actions, like displaying an image or changing colors, thereby improving
navigation and usability.
 Customizable Actions: Rollovers can trigger various actions like
displaying images, changing text, playing animations, or even opening
pop-ups.
 Common in Menus: Rollovers are often used in navigation menus and
buttons to improve visibility and user engagement.

Practical 14
1. Creating a Pull-Down Menu
Ans. A pull-down menu allows users to select one item from a list by clicking
on the drop-down. It’s often implemented using the <select> and <option>
HTML elements.

Example of a Pull-Down Menu:


<html>
<body>
<h3>Select a Fruit:</h3>
<select id="fruitMenu">
<option value="apple">Apple</option>
<option value="banana">Banana</option>
<option value="mango">Mango</option>
<option value="orange">Orange</option>
</select>

<script type="text/javascript">
document.getElementById("fruitMenu").onchange = function() {
alert("You selected: " + this.value);
};
</script>
</body>
</html>

Output: -

In this example:

 The <select> element creates a pull-down menu where users can pick
a fruit.
 When a user selects a fruit, an alert displays the selected option.
2. Floating Menu

Ans. A floating menu remains in a fixed position on the page as the user
scrolls, providing easy access to navigation or important actions. This effect
is typically achieved with CSS position: fixed or position: sticky and
can be enhanced with JavaScript.

Example of a Floating Menu:


<html>
<body>
<select id="sel1" onchange="sel_s1();" style="position: fixed;">
<option value="CO">CO</option>
<option value="CE">CE</option>
<option value="EE">EE</option>
<option value="ME">ME</option>
</select>
</body>
</html>

Output: -

3. Chain Select Menu

Ans. A chain select menu (also called a cascading dropdown) is a series of


related drop-down menus where the selection in one menu affects the
options in the following menu. For instance, choosing a country may change
the options in a state/province dropdown.

Example of a Chain Select Menu:


<html>
<body>
<h3>Select Location:</h3>
<label for="country">Country:</label>
<select id="country" onchange="updateStates()">
<option value="">--Select Country--</option>
<option value="usa">USA</option>
<option value="canada">Canada</option>
</select>

<label for="state">State/Province:</label>
<select id="state">
<option value="">--Select State--</option>
</select>

<script type="text/javascript">
function updateStates() {
const country = document.getElementById("country").value;
const stateSelect = document.getElementById("state");

// Clear previous options


stateSelect.innerHTML = "<option value=''>--Select State--</option>";

// Define states for each country


const states = {
usa: ["California", "Texas", "New York"],
canada: ["Ontario", "Quebec", "British Columbia"]
};

// Populate states based on selected country


if (country in states) {
states[country].forEach(function(state) {
let option = document.createElement("option");
option.value = state.toLowerCase();
option.text = state;
stateSelect.appendChild(option);
});
}
}
</script>
</body>
</html>

Output: -
Practical 15

1. List ways of protecting your web page and describe any one of them

Ans. 1. Use strong passwords

Use passwords that are at least eight characters long and include a combination
of letters, numbers, and special characters. Avoid using words that are easy to
find in a dictionary or that reference personal information.
2. Use a web application firewall (WAF)
3. Install an SSL certificate
4.Run regular backups
5.Update your software
6.Use multi-factor authentication (MFA)
7.Limit login attempts
8.Educate your employees
2. JavaScript Program to Hide the Email Address

Ans. The following script hides part of an email address, making it less visible to web
scrapers but still understandable for users:

<html>
<body>
<p id="emailDisplay">Email: </p>

<script type="text/javascript">
// Email hiding function
function hideEmail(user, domain) {
const email = user + "@" + domain;
document.getElementById("emailDisplay").innerText += email;
}

// Hides part of the email by passing values


hideEmail("example", "domain.com");
</script>
</body>
</html>

Output: -

In this example:

 The function hideEmail constructs the email using parameters for the
user and domain, hiding it from direct display in HTML.

3. JavaScript Program to Disable Right Mouse Click

Ans. This script disables the right-click context menu on the web page,
preventing users from using "right-click" actions like "Save As" or "View
Source":

<html>
<script type="text/javascript">
window.onload = function () {
document.addEventListener("contextmenu", function (e) {
e.preventDefault();
}, false);
}
</script>
<body>
<h3>Right click on screen,Context Menu is disabled</h3>
</body>
</html>
Practical 16

1. Explain how to link banner advertisement to URL with suitable


example in JavaScript

Ans. To link a banner advertisement to a URL, you can use


JavaScript to dynamically assign a URL to the banner image. This
method can be beneficial when you want to rotate or change the
banner link dynamically.

Example:

<html>
<body>
<a id="bannerLink" href="#" target="_blank">
<img id="bannerAd" src="banner1.jpg" alt="Advertisement Banner"
width="300" height="100">
</a>

<script type="text/javascript">
// Function to link the banner to a URL
function setBanner(url, imageSrc) {
document.getElementById("bannerLink").href = url; // Set the link
for the banner
document.getElementById("bannerAd").src = imageSrc; // Set the banner
image
}

// Set a banner with specific URL


setBanner("https://example.com", "banner2.jpg");
</script>
</body>
</html>

Output: -
2. Create a slideshow with the group of three images. Also
simulate the next and previous transition between slides in your
java script.

Ans. This example creates a slideshow with three images. JavaScript


functions control "Next" and "Previous" buttons to transition between slides.

<html>
<body>
<div>
<img id="slideshowImage" src="image1.jpg" width="300" height="200"
alt="Slideshow Image">
</div>

<br>
<button onclick="prevSlide()">Previous</button>
<button onclick="nextSlide()">Next</button>

<script type="text/javascript">
// Array of image sources
const images = ["image1.jpg", "image2.jpg", "image3.jpg"];
let currentIndex = 0;

// Function to show the next image


function nextSlide() {
currentIndex = (currentIndex + 1) % images.length; // Loop back to
start if end reached
document.getElementById("slideshowImage").src = images[currentIndex];
}

// Function to show the previous image


function prevSlide() {
currentIndex = (currentIndex - 1 + images.length) % images.length; //
Loop back to end if start reached
document.getElementById("slideshowImage").src = images[current Index];
}
</script>
</body>
</html>

Output: -

You might also like