[Go to site: main page, start]

0% found this document useful (0 votes)
6 views58 pages

Java Script Imp

The document covers various concepts in JavaScript, including the masking of variables within functions, the treatment of functions as objects, and the use of arrays as stacks and queues. It explains the definition and usage of functions, common properties and methods of objects, and the concept of anonymous functions. Additionally, it discusses regular expressions, string methods, and their applications in JavaScript.

Uploaded by

22122170
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views58 pages

Java Script Imp

The document covers various concepts in JavaScript, including the masking of variables within functions, the treatment of functions as objects, and the use of arrays as stacks and queues. It explains the definition and usage of functions, common properties and methods of objects, and the concept of anonymous functions. Additionally, it discusses regular expressions, string methods, and their applications in JavaScript.

Uploaded by

22122170
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

UNIT-3

Q.1) Explain the Mask out with respect to functions in Java Script.
Ans). Mask Out :
- When both local and global variables have the same name, the local variable
takes precedence over the global one inside the function. This is known as "mask
out".
- Example:
var x = "As global I am a string"; // Global variable
function maskDemo() {
var x = 5; // Local variable with the same name as global variable
[Link]("In function, x = " + x + "<br>"); // 5
}
[Link]("Before function call, x = " + x + "<br>"); // As global I am a string
maskDemo();
[Link]("After function call, x = " + x + "<br>"); // As global I am a string
- Here, the local variable ‘x’ inside ‘maskDemo’ "masks out" the global ‘x’ within
the function, and the value of global ‘x’ remains unchanged after the function call.
- To avoid confusion and conflicts, it’s a good practice to use unique variable
names, especially when reusing scripts.

Q.2) Explain how function is used as object in Java Script.


Ans). Functions as Objects
- In JavaScript, functions are treated as objects.
- This means that, like other objects, functions can be assigned to variables,
passed as arguments, and returned from other functions.
- Functions can also be created using the ‘Function’ constructor.
Syntax
var functionName = new Function("argument1", "argument2", "body of
function");
- The ‘Function’ constructor expects a variable number of string arguments. The
last argument is the body of the function, containing JavaScript statements.
- A function defined using the ‘Function()’ constructor does not require a name;
the name is set by the variable name.
Example with arguments
var sayHello2 = new Function("msg", "alert('Hello there ' + msg);");
sayHello2('Thomas');
Example without arguments
var sayHello = new Function("alert('Hello there');");
sayHello();
Reusing Functions
Functions can be assigned to other variables, allowing them to be reused or called
with different names.
var sayHelloAgain = sayHello;
sayHelloAgain();
- The key advantage of using the ‘Function()’ constructor is that it allows the
creation of functions dynamically, even after the page is loaded.

Q.3) How Arrays can be used as Stacks and Queues in Java.


Ans). - An array is a collection of elements that are stored in a fixed-size sequential
format. These elements can be of the same type or different types.
Declaring Arrays
Arrays can be declared in different ways:
1. Using Array Literal:
var myArray = [2, 4, 6, 8, "ten"];
2. Using the ‘new Array()’ Constructor:
var myArray = new Array();
3. Using ‘new Array(size)’ to create an array of a specific size:
var myArray = new Array(5); // Creates an array of size 5
4. Empty Array:
var myArray = [];

Q.4) What is function? Explain with example how to pass and return parameters
and arguments from called function go the calling function.
Ans). Functions
- Functions in JavaScript are reusable code blocks used to perform specific tasks
multiple times.
- Functions should ideally be self-contained, with clear input (parameters) and
output.
- JavaScript allows modular code through functions and supports advanced
features like variable parameter lists.
- Function names should follow the same rules as variable names, and descriptive
names are recommended to reflect the function’s purpose.
- The syntax to define a function is as follows:
function functionName(parameter-list) {
// statements
}
- The function body is written inside curly braces ‘{}’.
- Functions do not allow forward references to parameters.
Calling a Function
- A function must be defined before calling it unless it is defined in a ‘<script>‘ tag,
where forward references can be made.
Parameter Passing:-
- Parameters are data sent to a function to perform operations, while arguments
are the values provided when the function is called.
- JavaScript does not require a data type while defining parameters.
- If a parameter is defined without an argument being passed, its value will be
‘undefined’.
- Example of a simple function with a parameter:
function sayHello(name) {
if (name != "")
alert("Hello " + name);
else
alert("Don't be shy");
}
sayHello("George"); // This will show: Hello George
- A function can also take multiple parameters. For example:
function addThree(arg1, arg2, arg3) {
alert(arg1 + arg2 + arg3);
}
var x = 5, y = 7;
addThree(x, y, 11); // This will show: 23
- Arguments can be literal values, variables, or a combination of both.
Return Statement in Functions :-
- Functions often process input and generate a result, which can be returned using
the ‘return’ statement.
- The ‘return’ statement stops the function’s execution and outputs a value.
- You can return primitive values (e.g., numbers, strings) or object types (e.g.,
arrays, objects).
- Example:
function addThree(arg1, arg2, arg3) {
return arg1 + arg2 + arg3;
}
var x = 5, y = 7;
var result = addThree(x, y, 11); // result = 23
- If no ‘return’ statement is included, the function returns ‘undefined’ by default.

Q.5) What are Common properties and methods of object in JavaScript?


Ans). All JavaScript objects share some common properties and methods. These
help when working with objects, both built-in and custom.
Common Properties and Methods :
1. prototype
- This property points to the object from which the object inherits non-instance
properties.
2. constructor
- This refers to the function that created the object.
3. toString()
- Converts the object into a string, with behavior depending on the object.
4. toLocaleString()
- Converts the object into a localized string (depending on locale).
5. valueOf()
- Converts the object into a primitive type, usually a number.
6. hasOwnProperty(prop)
- Returns ‘true’ if the object has the specified property.
7. isPrototypeOf(obj)
- Returns ‘true’ if the object is the prototype of another object.
8. propertyIsEnumerable(prop)
- Returns ‘true’ if the specified property will show up in a ‘for/in’ loop.

Q.6) Write a Java Script program to pass the function by reference, perform
addition of two-objects imide the function and display the result in calling
function.
Ans). - In JavaScript, when we pass an object to a function, we are passing it by
reference.
- This means that any changes made to the object inside the function will directly
affect the original object.
- In this example, we'll create a JavaScript program that performs the addition of
two objects containing numeric values and then displays the result in the calling
function.
// Function to add properties of two objects
function addObjects(obj1, obj2) {
// Performing addition of the properties of two objects
[Link] = [Link] + [Link];
[Link] = [Link]; // Updating second object with the same result
}
// Main code
// Creating two objects with 'value' properties
let object1 = { value: 10 };
let object2 = { value: 20 };
// Displaying initial values
[Link]("Before Addition:");
[Link]("Object 1 value: " + [Link]);
[Link]("Object 2 value: " + [Link]);
// Calling the function and passing objects by reference
addObjects(object1, object2);
// Displaying the result after addition
[Link]("\nAfter Addition:");
[Link]("Object 1 value: " + [Link]); // Result is stored in object1
[Link]("Object 2 value: " + [Link]); // Result is also updated in object2
Output
Object 1 value: 10
Object 2 value: 20

Q.7) What is Anonymous Functions in JavaScript? Explain its use with an


example.
Ans). A.) Function Literals & Anonymous Functions
- A function literal defines an unnamed function, and this type of function is also
referred to as an anonymous function.
Syntax
var variablename = function(argumentList) {
// Function body
};
Example:-
<!DOCTYPE html>
<html>
<head><title>Simple Event and Anonymous Functions</title></head>
<body>
<input type="button" id="button" value="Press me">
<script type="text/javascript">
[Link]("button"). >{
alert('Button pressed!');
};
</script>
</body>
</html>
B) Arrow Functions
- Arrow functions, introduced in ES6, offer a more concise syntax for writing
functions.
- They use the ‘=>‘ syntax and do not require the ‘function’ keyword. However,
arrow functions have some differences compared to traditional functions:
- They do not have their own ‘this’ context, but inherit it from the surrounding
code.
- They cannot be used as constructors (i.e., with the ‘new’ keyword).
- They are always anonymous.
Example of arrow function
var hello = (name) => {
return "Hello " + name;
};
alert(hello("World")); // "Hello World"
- Arrow functions provide a more concise way to write functions, especially when
they are used as callbacks or in simple operations.
Q.8) Explain different types of Objects.
Ans). 1. User-defined Objects :- These are objects created by the programmer to
bring structure and consistency to a particular task.
2. Built-in Objects :- These objects are provided by JavaScript and are part of the
language itself.
3. Browser Objects :- These objects are not part of JavaScript itself but are
typically supported by most browsers.
4. Document Objects (DOM) :- These objects are part of the Document Object
Model (DOM), which is a W3C specification that allows JavaScript to interact with
HTML and XML documents. Through the DOM, JavaScript can manipulate the
structure of the document, access elements, and modify them dynamically.

Q.9) List the various methods of Math object. Explain any of Math object one
with example.
Ans). The Math object in JavaScript is a built-in object that provides various
mathematical functions and constants.
- It is not a constructor, meaning you can't create an instance of it. Instead, its
properties and methods are accessed directly from the Math object.
Mathematical Constants in JavaScript
JavaScript provides several mathematical constants that can be accessed via the
Math object:
- ’Math.E’: Euler's number, approximately ‘2.718’.
- ’[Link]’: The mathematical constant PI, approximately ‘3.14159’.
- ’Math.SQRT2’: The square root of 2, approximately ‘1.414’.
- ’Math.SQRT1_2’: The square root of 1/2, approximately ‘0.707’.
- ’Math.LN2’: The natural logarithm of 2, approximately ‘0.693’.
- ’Math.LN10’: The natural logarithm of 10, approximately ‘2.303’.
- ’Math.LOG2E’: The base-2 logarithm of Euler's number, approximately ‘1.442’.
- ’Math.LOG10E’: The base-10 logarithm of Euler's number, approximately ‘0.434.
UNIT-4
Q.1) What is Regular Expression in JavaScript expressions. Explain the need of
regular expressions.
Ans). -Regular expressions (RegExp) are patterns used for matching and
manipulating strings.
- They are commonly used for validating input, parsing text, and performing
search-and-replace operations.
- JavaScript introduced regular expressions with the ‘RegExp’ object.
Features of Regular Expressions:
1. Pattern Matching: Matches specific sequences of characters in a string.
2. Validation: Validates user input like phone numbers, email addresses, etc.
3. Search and Replace: Simplifies tasks like finding specific patterns and replacing
them with new content.
4. Compact Code: Allows complex operations in fewer lines of code compared to
traditional string manipulation.

Need for Regular Expressions in JavaScript


- Regular expressions are powerful tools that simplify string matching, validation,
and manipulation.
- Their utility lies in reducing code complexity and enabling concise handling of
complex patterns.

Q.2) Explain Look ahead and Look behind concepts in JavaScript.


Ans) A). Lookahead :-
- A lookahead group is a non-capturing group that allows you to match a part of a
string only if it is followed by a specific sequence of characters, without including
that sequence in the match itself.
- There are two types of lookaheads: positive lookahead and negative lookahead.
i. Positive Lookahead:-
- Syntax: ‘(?=...)’
- A positive lookahead ensures that a given expression is followed by a
specific pattern but does not include that pattern in the match.

ii. Negative Lookahead :-


- Syntax: ‘(?!...)’
- A negative lookahead ensures that a given expression is not followed by a
specific pattern. The pattern will not match if it is followed by that
sequence.

B). Lookbehind :-
- A lookbehind group is a non-capturing group that allows you to match a part of a
string only if it is preceded by a specific sequence of characters, without including
that preceding sequence in the match itself.
- Similar to lookaheads, there are positive lookbehind and negative lookbehind
assertions.
I. Positive Lookbehind
- Syntax: ‘(?<=...)’
- A positive lookbehind ensures that a given pattern is preceded by a
specific sequence but does not include that sequence in the match.
II. Negative Lookbehind
- Syntax: ‘(?<!...)’
- A negative lookbehind ensures that a given pattern is not preceded
by a specific sequence. The match will not occur if the pattern is
preceded by that sequence.
Q.3) Write a program to study string related built in methods in JavaScript.
Ans). // Step 1: Declare a string
let myString = " Hello, JavaScript World! ";
// Step 2: Using charAt() method to get a character at a specific index
[Link]("Character at index 6: " + [Link](6)); // Output: "J"
// Step 3: Using concat() method to combine two strings
let newString = [Link](" Enjoy Learning!");
[Link]("Concatenated String: " + newString);
// Step 4: Using includes() method to check if the string contains a specific word
[Link]("Does the string contain 'JavaScript'? " +
[Link]("JavaScript")); // Output: true
// Step 5: Using indexOf() method to find the position of the first occurrence of a
substring
[Link]("Index of 'World': " + [Link]("World")); // Output: 19
// Step 6: Using toUpperCase() method to convert string to uppercase
[Link]("Uppercase String: " + [Link]());
// Step 7: Using toLowerCase() method to convert string to lowercase
[Link]("Lowercase String: " + [Link]());
// Step 8: Using slice() method to extract part of the string
let slicedString = [Link](3, 10);
[Link]("Sliced String (from index 3 to 10): " + slicedString); // Output: "llo, Ja"
// Step 9: Using replace() method to replace part of the string
let replacedString = [Link]("JavaScript", "[Link]");
[Link]("Replaced String: " + replacedString);
// Step 10: Using trim() method to remove whitespaces from both ends of the
string
let trimmedString = [Link]();
[Link]("Trimmed String: '" + trimmedString + "'");
// Step 11: Using split() method to split the string into an array based on a space
let stringArray = [Link](" ");
[Link]("String Split into Array: ", stringArray);
Output:
Character at index 6: J
Concatenated String: Hello, JavaScript World! Enjoy Learning!
Does the string contain 'JavaScript'? true
Index of 'World': 19
Uppercase String: HELLO, JAVASCRIPT WORLD!
Lowercase String: hello, javascript world!
Sliced String (from index 3 to 10): llo, Ja
Replaced String: Hello, [Link] World!
Trimmed String: 'Hello, JavaScript World!'
String Split into Array: [ 'Hello,', 'JavaScript', 'World!' ]

Q.4) Explain string methods for Regular Expression in JavaScript.


Ans). - The ‘String’ object offers several methods that work with regular
expressions, providing powerful tools for string manipulation.
- These methods not only match patterns but can also modify strings based on
those patterns.
1. ‘search()’
- Purpose: Finds the index of the first match of a regular expression within a string.
- Returns: The index of the first matching substring or ‘-1’ if no match is found.
- Example:
var pattern = /pow.*/i;
var str = "JavaScript regular expressions are powerful!";
var result = [Link](pattern);
[Link](result); // Prints: 35 (index of "powerful!")
2. ‘split()’
- Purpose: Splits a string into an array of substrings using a regular expression
as the delimiter.
- Example:
var str = "I am, string, break it.";
var result = [Link](",");
[Link](result); // Prints: ["I am", " string", " break it."]
- With Regular Expressions: You can split based on patterns like spaces or slashes.
javascript
var limiter = /[\/]+/; // one or more slashes
var str = "10/3/14/7/9";
var result = [Link](limiter);
[Link](result); // Prints: ["10", "3", "14", "7", "9"]
3. ‘replace()’
- Purpose: Replaces the first occurrence of a pattern in a string with a replacement
string.
- Example:
var pattern = /\./;
var newStr = "1";
var str = "Hello. Regexps are fun.";
var result = [Link](pattern, newStr);
[Link](result); // Prints: "Hello1 Regexps are fun."
Q.5) Explain Character Classes in JavaScript.
Ans) - Character classes allow you to match any character from a specified set or
group.
- They are defined within square brackets ‘[]’. Anything inside the brackets is
treated as a single unit that can match any one character from the set.
1. Matching Specific Characters:-
A character class can match any of the individual characters it contains.
Example 1:
var pattern = /[pbm]111/;
var str = "p111";
var result = [Link](pattern);
[Link](result); // Output: ['p111']
- Explanation: The class ‘[pbm]’ matches any one of the characters ‘p’, ‘b’, or ‘m’
followed by ‘111’. This will match ‘p111’, ‘b111’, and ‘m111’, but not ‘c111’.
2. Matching Digits:-
- You can define a class to match digits using ‘0-9’ or specify them individually.
Example :
var pattern = /[1234567890]+/;
var str = "123456";
var result = [Link](pattern);
[Link](result); // Output: ['123456']
- Explanation: The pattern ‘[1234567890]’ matches any digit from 0 to 9. The ‘+’
quantifier means the pattern will match one or more digits.
3). Using Dash (‘-’) for Ranges :-
- Instead of listing each character individually, you can use a dash (‘-’) to specify a
range of characters.
Example :
var pattern = /[0-9]+/;
var str = "987654";
var result = [Link](pattern);
[Link](result); // Output: ['987654']
- Explanation: The pattern ‘[0-9]’ matches any digit, the same as ‘[1234567890]’,
but more compactly. This matches strings containing one or more digits.

Q.6) What are the limitations of Regular Expression?


Ans). 1. Complexity: Some regular expressions have exponential complexity,
making them slow for large datasets.
2. Readability: Complex regex patterns can be hard to understand and maintain.
3. Performance: Regex with excessive backtracking or alternatives can be slow.
4. Real-world Validation:
- Email Addresses: Difficult to validate due to complex formats (e.g., ‘!’ or ‘+’
symbols, IP addresses).
5. Semantic Validity: Regex can validate the format but not check if the data is
logically correct (e.g., ‘31/02/2021’).

Q.7) What are common character classes in Regular Expressions?


Ans). - Character classes provide shorthand escape codes to make patterns more
concise and easier to understand.
- Here are the most commonly used shorthand character classes:
1. ‘.’ (Period)
- The period matches any single character except for newline characters. This is
useful when you want to match any character in a string.
2. ‘\w’ (Word Character)
- Matches any word character, which is equivalent to ‘[a-zA-Z0-9_]’. This includes
lowercase and uppercase letters, digits, and the underscore ‘_’.
3. ‘\W’ (Non-Word Character)
- Matches any character that is not a word character, i.e., anything that is not ‘[a-
zA-Z0-9_]’.
4. ‘\s’ (Whitespace Character)
- Matches any whitespace character, which includes spaces, tabs, line breaks, etc.
It is equivalent to ‘[ \t\n\r\f\v]’.
5. ‘\S’ (Non-Whitespace Character)
- Matches any character that is not a whitespace character, i.e., it is equivalent to
‘[^ \t\n\r\f\v]’.
6. ‘\d’ (Digit)
- Matches any digit, equivalent to ‘[0-9]’.

Q.8) Write a short note on Advanced Regular Expressions.


Ans). 1. Multiline Matching
- Purpose: The multiline flag (‘m’) allows the characters ‘^’ and ‘$’ to match not
only the beginning and end of the entire string but also the beginning and end of
each line within the string.
2. Non-Capturing Parentheses
- Purpose: Non-capturing parentheses, written as ‘(?:...)’, are used when you want
to group parts of a regular expression without saving those parts for back
referencing. This can be useful when you do not need to refer back to a part of the
match but still want to group expressions together for clarity.
3. Lookaround Groups
- Purpose: Lookaround groups are used to match text only if it is followed or
preceded by a specific pattern, without including the followed or preceded text in
the match.

Q.9) List the 6 Repetition Quantifiers with their meaning. Explain any 2 with
example.
Ans) 1. Asterisk (‘*’) – Zero or More Occurrences:
This quantifier allows the preceding character to appear any number of times,
including zero.
var pattern = /ab*c/;
var string = "abc ac abbbc";
[Link]([Link](pattern)); // Output: 'abc'
- Matches "a", followed by zero or more "b", followed by "c".
- Examples of strings that match: "ac", "abc", "abbbc".
2. Plus (‘+’) – One or More Occurrences:
This quantifier ensures the preceding character appears at least once.
var pattern = /ab+c/;
var string = "abc ac abbbc";
[Link]([Link](pattern)); // Output: 'abc'
- Matches "a", followed by one or more "b", followed by "c".
- Examples of strings that match: "abc", "abbbc".
- Does not match "ac" since there is no "b".
3. Question Mark (‘?’) – Zero or One Occurrence:
The question mark makes the preceding character optional.
var pattern = /ab?c/;
var string = "ac abc abbc";
[Link]([Link](pattern)); // Output: 'ac'
- Matches "a", followed by zero or one "b", followed by "c".
- Examples of strings that match: "ac", "abc".
- Does not match "abbc" as there are too many "b" characters.
4. Curly Braces (‘{m}’) – Exact Number of Occurrences:
This quantifier specifies an exact number of times the preceding character should
appear.
var pattern = /ab{3}c/;
var string = "abbbc abbc abc";
[Link]([Link](pattern)); // Output: 'abbbc'
- Matches "a", followed by exactly three "b", followed by "c".
- Only "abbbc" matches this pattern.
5. Curly Braces with Range (‘{m,n}’) – Between ‘m’ and ‘n’ Occurrences:
This quantifier specifies a range for how many times the preceding character can
appear.
var pattern = /ab{2,4}c/;
var string = "abc abbc abbbc abbbbc";
[Link]([Link](pattern)); // Output: 'abbc'
- Matches "a", followed by between 2 and 4 "b", followed by "c".
- Examples of strings that match: "abbc", "abbbc", "abbbbc".
- Does not match "abc" since it has less than 2 "b".
6. Curly Braces with Lower Limit Only (‘{m,}’) – At Least ‘m’ Occurrences:
This quantifier ensures the preceding character appears at least ‘m’ times with no
upper limit.
var pattern = /ab{3,}c/;
var string = "abc abbc abbbc abbbbc";
[Link]([Link](pattern)); // Output: 'abbbc'
- Matches "a", followed by at least three "b", followed by "c".
- Examples of strings that match: "abbbc", "abbbbc".
Q.10) Explain Static Properties of the RegExp Class Object.
Ans). - These properties are accessed from the ‘RegExp’ class and are used to
handle results from the most recent match.
1. $1, $2, ..., $9
- Description: Holds the text matched by the first to the ninth parenthesized
subexpression.
- Example:
javascript
var pattern = /(cat)(dog)/g;
[Link]("this is a cat dog and cat dog");
[Link](RegExp.$1); // "cat"
[Link](RegExp.$2); // "dog"
2. index
- Type: Integer
- Description: The position of the first character of the last match.
- Example:
javascript
var pattern = /(cat)(dog)/g;
[Link]("this is a cat dog and cat dog");
[Link]([Link]); // 10
3. input
- Type: String
- Description: The string that was tested against the regular expression.
- Example:
javascript
var pattern = /(cat)(dog)/g;
[Link]("this is a cat dog and cat dog");
[Link]([Link]); // "this is a cat dog and cat dog"
4. lastIndex
- Type: Integer
- Description: Specifies the position in the string where the next match will begin,
for global matches.
- Example:
javascript
var pattern = /(cat)(dog)/g;
[Link]("this is a cat dog and cat dog");
[Link]([Link]); // 17
5. lastMatch
- Type: String
- Description: Contains the most recently matched text.
- Example:
javascript
var pattern = /(cat)(dog)/g;
[Link]("this is a cat dog and cat dog");
[Link]([Link]); // "cat dog"
6. lastParen
- Type: String
- Description: Contains the text of the last parenthesized subexpression of the
most recent match.
- Example:
javascript
var pattern = /(cat)(dog)/g;
[Link]("this is a cat dog and cat dog");
[Link]([Link]); // "dog"
UNIT-5
Q.1) Define JavaScript object model and explain four distinct object models used
in JavaScript.
Ans). - JavaScript interacts with various parts of the browser and document
through several layers of objects. These are divided into categories:
1. Core JavaScript Language:
- This is the basic structure of JavaScript, including:
- Data Types: Defines the types of values, such as numbers, strings, booleans, and
objects.
- Operators: Include arithmetic operators (e.g., +, -, *, /), comparison operators
(e.g., ==, ===), logical operators (e.g., &&, ||), etc.
- Statements: Control the flow of the program (e.g., if-else, loops).
- Functions: Encapsulated blocks of code that can be executed when called.
2. Built-in Objects:
- JavaScript provides built-in objects that help manage data and other tasks. These
include:
- Math: Provides mathematical constants and functions (e.g., [Link],
[Link]()).
- String: Offers methods for string manipulation (e.g., ‘toUpperCase()’,
‘substring()’).
- Number: Used for handling numerical values.
- Array: A collection of values indexed by numbers, with methods to manipulate
them.
- Date: For working with dates and times.
- RegExp: Provides regular expression functionality for pattern matching.
3. Browser Object Model (BOM):
- The BOM provides objects that help interact with the browser and its
environment. These include:
- Window: Represents the entire browser window, providing methods for
controlling the window, such as opening new tabs or resizing the window.
- Navigator: Provides information about the browser, such as its name, version,
and capabilities.
- Location: Allows access to the current URL of the page and methods to
change it (e.g., ‘[Link]’).
- History: Provides methods to navigate through the browser’s history (e.g.,
‘[Link]()’ and ‘[Link]()’).
- Screen: Gives information about the user’s screen, like screen width and height.
4. Document Object Model (DOM):
- The DOM represents the structure of the HTML document and is essential for
web page manipulation. It allows JavaScript to:
- Access Elements: JavaScript can access and modify HTML elements on the page
(e.g., by using ‘[Link]()’ or ‘[Link]()’).
- Modify Content: JavaScript can change the text, images, and other content on
the page.
- Manipulate Structure: JavaScript can add, remove, or rearrange HTML elements
using methods like ‘appendChild()’, ‘removeChild()’, or ‘createElement()’.

Q.2) Explain event and event handler with an example.


Ans). Event Handlers
- Event handlers are the primary way in which JavaScript responds to user actions,
such as clicks or mouse movements.
- An event handler is a piece of JavaScript code associated with a specific part of
the document and a particular event.
- The code is triggered when the event occurs at that part of the document.
- Instead of using HTML attributes like ‘onclick’ directly in markup, you can also
attach event handlers using JavaScript.
Example:
<form name="myForm" id="myForm" method="get" action="#">
<input name="myButton" id="myButton" type="button" value="Click me"/>
</form>
<script type="text/javascript">
[Link] = new Function("alert('That tickles!')");
</script>
- In this example, an anonymous function is assigned to the ‘onclick’ property of
the ‘myButton’ element.
- This approach allows more flexibility and avoids cluttering the HTML with inline
JavaScript.
Events:-
Click: When the user clicks on an element.
MouseOver: When the user places the mouse over an element.
MouseOut: When the user moves the mouse away from an element.
- These events are commonly used with form buttons, form fields, images, and
links.
- They are used for tasks like form validation and rollover effects for buttons.
- Not every object can handle every type of event. The types of events an object
can handle are typically linked to how that object is commonly used.
Example:
Here’s an example where a button click triggers an alert:
<form method="get" action="#">
<input type="button" value="Click me" tickles!');"/>
</form>
- When the user clicks the button, the browser sends a ‘Click’ event to the
button object, and its ‘onclick’ event handler is triggered.
- This is part of the Event Model in JavaScript, which defines how events are
handled and how event handlers are attached to objects.

Q.3) Write a JavaScript program to create a Home page of any website and
change background color using.
a)On mouse [Link] (mouse over)
b)On locus event (focus)
Ans). 1. ‘onmouseover’ Event:
Triggered when the mouse pointer is moved over an HTML element.
Example: Change the background color of the webpage when the user hovers over
a button.
2. ‘onfocus’ Event:
Triggered when an input field gets focused (clicked or tabbed into).
Example: Change the background color of the input field when the user clicks on
it.
Program Code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Home Page Example</title>
<style>
/* Styling for the body */
body {
font-family: Arial, sans-serif;
text-align: center;
margin: 0;
padding: 0;
}
/* Styling for the header */
h1 {
color: #333;
}
/* Styling for the button */
button {
background-color: lightblue;
border: none;
padding: 10px 20px;
font-size: 18px;
cursor: pointer;
margin: 20px;
border-radius: 8px;
}
button:hover {
background-color: lightgreen;
}
/* Styling for the input field */
input {
padding: 10px;
border: 2px solid #ccc;
font-size: 16px;
margin: 10px;
border-radius: 8px;
}
input:focus {
border-color: #6666ff;
background-color: #e6e6ff;
}
</style>
</head>
<body>
<!-- Page Content -->
<h1>Welcome to My Website</h1>
<p>Hover over the button or focus on the input field to see the color
changes.</p>
<!-- Button with onmouseover event -->
<button >Hover over me!
</button>
<!-- Input field with onfocus event -->
<br>
<input type="text" placeholder="Click or focus here"
><!-- JavaScript Code -->
<script>
// Function to change background color
function changeBackgroundColor(color) {
[Link] = color;
}
</script>
</body>
</html>

OUTPUT
1. Initial State:
- The homepage displays a title, a button, and an input field.
- The background color is white by default.
2. On Mouse Hover (Button):
- When the user hovers over the button, the background color of the webpage
changes to lightyellow.
3. On Input Focus:
- When the user clicks or tabs into the input field, the background color of the
webpage changes to lightpink.
Q.4) Describe Document properties and methods with their HTML Relationship.
Ans). - There are several types of Document properties relate to HTML or XML
documents:
1. Element Node (Type 1): Represents an element in the document, like ‘<html>‘,
‘<head>‘, ‘<body>‘, ‘<h1>‘, etc.
2. Attribute Node (Type 2): Represents an attribute of an element, such as
‘href="[Link] in an ‘<a>‘ tag.
3. Text Node (Type 3): Represents the actual text content inside an element. For
example, the text inside ‘<h1>DOM Test Heading</h1>‘ is a text node.
4. Comment Node (Type 8): Represents an HTML comment, like ‘<!-- This is a
comment -->‘.
5. Document Node (Type 9): The root node of the DOM tree, which represents the
entire document (typically the ‘<html>‘ element in an HTML document).
6. Document Type Node (Type 10): Represents the document type declaration
(like ‘<!DOCTYPE html>‘).
Q.5) Differentiate between HTML and DHTML.
Ans).

Q.6) Explain DOM and CSS Elements with example.


Ans). - Dynamic manipulation of CSS properties via the DOM allows developers to
create interactive and visually dynamic web pages.
- DOM Level 2 supports CSS property changes, and similar capabilities exist in
earlier object models like Microsoft's DHTML.
- The ‘style’ property of an HTML element in JavaScript enables inline CSS
manipulation.
- CSS property names often use hyphenated syntax, while DOM properties use
camelCase for JavaScript.
- A CSS property like ‘background-color’ is converted to ‘backgroundColor’ in
JavaScript.
- For reserved words in JavaScript, such as ‘float’, use ‘cssFloat’.

Q.7) Describe Netscape 4 Event Model in detail.


Ans). - Netscape 4 introduced the first event model with advanced features that
were not present in the basic event model.
- This model provided greater flexibility in handling events, especially with respect
to where and how events could be handled within the document object hierarchy.
- However, this model is considered obsolete and is only found in Netscape 4
browsers.
- Since Mozilla-based browsers adopted the DOM2 model and Netscape 6+ was
based on Mozilla, this model is now considered an evolutionary dead end.
- When an event occurs in Netscape 4, the browser creates an ‘Event’ object and
passes it to the handler.
- This event object contains several useful properties that help developers handle
events more efficiently.

Q.8) Explain the role of Event Handlers in Java Script.


Ans). 1. Traditional HTML attributes (e.g., ‘<form >2. UsE IN JavaScript to bind handlers
(e.g.,‘[Link]("myForm"). >3. Proprietary methods like Internet Explorer's ‘attachEvent()’.
4. DOM2 methods like ‘addEventListener()’ to attach event listeners.

Q.9) What is Document Tree? Explain DOM Methods to Create Nodes.


Ans). - In DOM Level 1 and Level 2, the most important concept is that we are
manipulating a document tree.
- This tree structure represents the entire document as a hierarchical set of nodes,
where each node corresponds to a part of the document, such as elements,
attributes, or text.
DOM Nodes Related to HTML Documents
- There are several types of nodes in the DOM that relate to HTML or XML
documents:
1. Element Node (Type 1): Represents an element in the document, like ‘<html>‘,
‘<head>‘, ‘<body>‘, ‘<h1>‘, etc.
2. Attribute Node (Type 2): Represents an attribute of an element, such as
‘href="[Link] in an ‘<a>‘ tag.
3. Text Node (Type 3): Represents the actual text content inside an element. For
example, the text inside ‘<h1>DOM Test Heading</h1>‘ is a text node.
4. Comment Node (Type 8): Represents an HTML comment, like ‘<!-- This is a
comment -->‘.
5. Document Node (Type 9): The root node of the DOM tree, which represents the
entire document (typically the ‘<html>‘ element in an HTML document).
6. Document Type Node (Type 10): Represents the document type declaration
(like ‘<!DOCTYPE html>‘).

Q.10) Explain DOM2 Event Model.


Ans). In the DOM2 model, events propagate through two main phases:
-Capture Phase: The event starts from the top (Document) and travels down
through the object hierarchy toward the target. This phase mimics the behavior
found in Netscape 4.
-Bubbling Phase: After reaching the target element, the event bubbles back up the
hierarchy to the top. This phase is similar to the event model used in Internet
Explorer 4+.
-During both phases, events can be intercepted, handled, or redirected by any
object along the way.
-The DOM2 Event Model describes a standardized method to handle events within
a hierarchical structure like an (X)HTML document.
- It defines how events are created, captured, processed, and canceled, along with
the event propagation behavior, which details how an event travels from its
source to the target and what happens afterward.
- This model incorporates the basic event model while introducing concepts from
proprietary models like those of Netscape 4 and Internet Explorer
UNIT-6
Q.1) Describe with example the methods alert() and confirm() of Window
object.
Ans). 1. Alert Dialog
- The ‘alert()’ method of the Window object creates a small window with a
message and an OK button.
- It is used to display simple notifications or debugging messages.
- The alert dialog is modal, meaning the user must dismiss it before interacting
with the rest of the page.
- Syntax:
alert(string);
- Example:
javascript
alert("Hello, World!");
2. Confirm Dialog
- The ‘confirm()’ method creates a window with a message and two buttons: OK
and Cancel. The user clicks either to confirm or cancel an action.
- This method is often used to ask the user for confirmation before proceeding
with an operation.
- Syntax:
confirm(string);
- Example:
let isConfirmed = confirm("Do you want to submit the form?");
- Return Value: The ‘confirm()’ method returns a Boolean value:
- ‘true’ if the OK button is clicked.
- ‘false’ if the Cancel button is clicked or the dialog is closed.
Q.2) Explain Common Window Properties Related to Frames.
Ans). In graphical user interface (GUI) design, "window properties" refer to
various attributes and behaviors associated with the display of a window or frame
on a screen. These properties control the appearance, size, position, and other
aspects of the window and are important for providing a user-friendly experience.
Here are some common window properties related to frames:
1. Title
• Description: The title of a window typically appears in the window's title
bar, at the top of the window. It often identifies the application or the
current document.
• Examples: "Untitled - Notepad," "[Link]"
2. Size
• Description: The dimensions of the window, typically measured in pixels,
specifying its width and height.
• Examples: A window might have a size of 800x600 pixels.
3. Position
• Description: The location of the window on the screen, usually represented
by X and Y coordinates (for example, (x=100, y=150)).
4. Borders
• Description: The edge of the window, which can be customizable in terms of
thickness, color, and style. Borders separate the window’s content from the
surrounding elements.
• Examples: Some applications have thin borders, while others have none at
all (e.g., borderless windows).
5. Frame Style
• Description: This refers to the appearance of the window's frame, which can
vary between different operating systems and applications.
• Examples:
o Normal frame: Includes title bar and borders.
o Borderless: No visible borders, and the window might be resized or
moved in non-standard ways.
o Tool window: A type of frame designed for smaller, utility-type
windows (often without a title bar or with a custom design).
6. Window State
• Description: This refers to the current state of the window in terms of
visibility, size, and interaction.
• Examples:
o Normal: The window is open in its usual size and position.
o Maximized: The window takes up the entire screen.
o Minimized: The window is reduced to an icon or a taskbar button.
o Fullscreen: The window covers the entire screen without any
surrounding interface elements, such as a taskbar or title bar.

Q.3) Write a short note on Form Usability and Java Script.


Ans). Form Usability
Form Usability refers to the design and functionality of online forms to ensure
they are easy to use, intuitive, and effective at gathering user inputs. A well-
designed form is essential for a positive user experience (UX) and can directly
influence user engagement, conversion rates, and customer satisfaction. Whether
it's a sign-up form, a contact form, or a checkout process, form usability focuses
on making the experience seamless and user-friendly.
Key aspects of form usability include:
1. Clear and Concise Labels:
o Labels should be straightforward, and use simple language to
describe each field's expected input (e.g., "Full Name" instead of
"Name").
o Properly aligned labels (e.g., left-aligned) help users quickly identify
the fields.
2. Logical Field Arrangement:
o Form fields should follow a natural and logical order that makes sense
to the user (e.g., First Name, Last Name, Email).
o Group similar fields together (e.g., address fields) to improve
readability.
3. Minimal Cognitive Load:
o Avoid asking for unnecessary information. Only ask for what’s
essential to prevent overwhelming users.
o Use auto-completion where appropriate, like auto-filling address
fields, to save time.
JavaScript:
JavaScript is a high-level, dynamic, and interpreted programming language that is
widely used to create interactive and dynamic content on the web. It was initially
developed by Netscape as a way to add interactivity to websites and is now an
essential part of modern web development. JavaScript is typically used alongside
HTML and CSS to build rich, user-friendly web pages and applications.
Key Features of JavaScript:
1. Client-Side Scripting:
o JavaScript runs in the user's web browser (client-side), allowing for
quick interactions without the need to communicate with the server
for every action. This enables features like form validation,
animations, and interactive maps.
2. Dynamic and Interactive Content:
o JavaScript enables the creation of interactive elements on websites,
such as dropdown menus, image sliders, modal windows, and real-
time updates (e.g., live chat or notifications).
3. Event-Driven:
o JavaScript responds to user actions like clicks, key presses, or page
loading, making it an event-driven language. For example, you can
use JavaScript to handle a form submission, change the content on a
page, or trigger animations when a user interacts with a page
element.

Q.4) Explain Label Fieldset, and Legend as other form elements.


Ans). Label, Fieldset, and Legend: Key HTML Form Elements
In HTML forms, the elements <label>, <fieldset>, and <legend> are used to
improve the accessibility, structure, and usability of forms. They help in grouping
related form elements, associating labels with input fields, and providing
meaningful descriptions for sections of a form. Here’s a breakdown of each
element:

1. <label> Element
The <label> element is used to define a label for a form control (such as an
<input>, <select>, <textarea>, etc.). It helps improve the accessibility of forms by
providing a clear description of what the user is expected to input in a form field.
Associating a label with a form control also enhances the user experience,
particularly for screen readers and users with disabilities.
Key Features:
• Associating with Input Fields: A <label> is usually associated with an input
field using the for attribute, which links the label to the input element’s id.
• Clickable Labels: Clicking on a label will focus the associated input field,
improving usability, especially for smaller clickable areas (like checkboxes or
radio buttons).
2. <fieldset> Element
The <fieldset> element is used to group related form controls and elements,
providing a visual structure to the form. It is often used when creating complex
forms with multiple sections, such as personal information, contact details, etc.
The <fieldset> helps users understand that certain fields belong together and can
make the form more readable.
Key Features:
• Grouping Form Controls: The <fieldset> element groups related form fields
together, typically for easier navigation and a cleaner layout.
• Styling and Structure: By default, the <fieldset> adds a border around the
grouped elements, visually separating them from other sections of the
form. You can also style it using CSS to customize its appearance.
1. clearly highlighted, and users should receive meaningful error messages to
correct mistakes (e.g., "Please enter a valid email address").
2. Auto-completion: Offering auto-completion, especially for repetitive fields
like addresses, can save users time and reduce errors.

3. <legend> Element
The <legend> element provides a caption or title for the contents of a <fieldset>.
It describes the group of form elements contained within a <fieldset>, giving users
a clear indication of what information the section represents. The <legend>
element is placed directly after the <fieldset> tag and is typically displayed as a
heading for the group.
Key Features:
• Descriptive Title for Grouped Elements: The <legend> gives context to the
fields within the <fieldset>, improving accessibility and clarity.
• Improves Form Structure: It enhances the semantic structure of the form,
which is helpful for screen readers and users navigating the form.

Q.5) What is a significance of form validation?


Ans). Significance of Form Validation
Form validation is the process of ensuring that the data entered into a form by a
user is accurate, complete, and in the correct format before it is submitted to a
server for processing. The significance of form validation lies in improving the user
experience, preventing errors, enhancing security, and ensuring the integrity of
the data being collected.
Here are the key reasons why form validation is important:

1. Improves Data Accuracy


• Ensures Correct Data Format: Form validation checks that data entered by
users follows the correct format (e.g., valid email addresses, phone
numbers, dates, or numerical values). This helps prevent invalid or
erroneous data from being submitted.
2. Enhances User Experience (UX)
• Instant Feedback: Clients-side validation provides immediate feedback to
users when they make a mistake, helping them correct errors in real time.
This improves the overall experience and makes forms less frustrating.
3. Prevents Invalid Submissions
• Reduces Server Load: Validating form data before it reaches the server
reduces unnecessary server requests. Invalid data won’t be processed,
saving time and resources on the server-side and improving performance.
• Prevents Invalid or Incomplete Submissions: Without validation, users
might accidentally leave important fields empty or submit incorrect
information, leading to incomplete or unusable submissions.

Q.6) Explain Various methods to control windows and list out window features.
Ans). - JavaScript provides several methods to manipulate windows.
- These methods allow you to control window behavior such as focusing, moving,
resizing, scrolling, and changing the window's location.
1. ‘[Link]()’:
- This method brings a window into focus, making it the active window that the
user can interact with.
- Example: If a window has been opened, you can call this method to bring it to
the front.
2. ‘[Link]()’:
- This method removes focus from the current window, which means the window
will no longer be the active one.
- Example: If you want to shift the focus from a window to another, you would use
‘[Link]()’.

- When opening a new window using JavaScript's ‘[Link]()’ method, the


‘features’ parameter allows you to customize the window's behavior and
appearance.
- Here are some of the available features you can specify:
1.) alwaysLowered:
Determines if the window should always stay beneath other windows. It may pose
a security risk.
2.) alwaysRaised:
Makes the window always stay on top of other windows.
3.) dependent:
Makes the window dependent on its parent. If the parent window is closed, the
dependent window also closes.
4.)directories:
Controls whether the directories button in the browser's window is shown.
5.)fullscreen:
Makes the window take over the entire screen (only in Internet Explorer).

6.)height:
Sets the height of the entire window, including the chrome (the window border
and title bar).

Q.7) Explain the form handling and the terms form fields, validations, Dynamic
forms. Form usability with an example
Ans). - One of the most common uses of JavaScript is for form validation, which
allows you to check the contents of a form before sending it to the server.
- This is crucial for ensuring the data is correct and complete, improving user
experience, and reducing server load.
Benefits of JavaScript Form Validation:
- Reduce round trips to the server: Validating forms client-side reduces the
number of requests sent to the server for invalid data.
- Improve usability: Immediate feedback is provided to the user, guiding them to
fix errors before submission.
- Rectify form data: JavaScript can automatically fix common input mistakes,
reducing user frustration.
- Reduce server load: By ensuring the data is correct client-side, the number of
invalid submissions sent to the server is minimized.
Form Basics:
- Forms in HTML are accessed through the ‘Form’ object in JavaScript, which is a
part of the ‘Document’ object model (DOM).
Form Tag Structure:
<form id="formID" name="formName" action="submitURL" method="POST">
<!-- form fields -->
</form>
Form Properties and Methods:
- ‘action’: The URL to which the form data will be submitted.
- ‘method’: The method to submit form data (GET or POST).
- ‘enctype’: Defines how the form data should be encoded when submitting to the
server (e.g., ‘application/x-www-form-urlencoded’ or ‘multipart/form-data’).
- ‘target’: Specifies where to display the response (e.g., in a new window or within
a frame).
Q.8) Design and implement a simple calculator sing java script for operations like
addition, multiplication, subtraction, division, square of a number
Ans). Program Code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Simple Calculator</title>
<style>
body {
font-family: Arial, sans-serif;
text-align: center;
margin: 0;
padding: 0;
}
h1 {
margin-top: 20px;
color: #333;
}
.calculator {
width: 300px;
margin: 50px auto;
padding: 20px;
border: 2px solid #ccc;
border-radius: 10px;
box-shadow: 0 5px 10px rgba(0, 0, 0, 0.1);
}
input[type="number"], .result {
width: 90%;
padding: 10px;
margin: 10px 0;
border: 1px solid #ccc;
border-radius: 5px;
font-size: 16px;
}
button {
padding: 10px 20px;
margin: 5px;
border: none;
background-color: #007BFF;
color: white;
border-radius: 5px;
font-size: 16px;
cursor: pointer;
}
button:hover {
background-color: #0056b3;
}
</style>
</head>
<body>
<h1>Simple Calculator</h1>
<div class="calculator">
<input type="number" id="num1" placeholder="Enter first number">
<input type="number" id="num2" placeholder="Enter second number">
<div class="result" id="result">Result: </div>
<button > <button ><button ><button ><button ></div>
<script>
function performOperation(operation) {
// Get input values
const num1 = parseFloat([Link]("num1").value);
const num2 = parseFloat([Link]("num2").value);
let result;
// Perform operation based on user selection
if (operation === "add") {
result = num1 + num2;
} else if (operation === "subtract") {
result = num1 - num2;
} else if (operation === "multiply") {
result = num1 * num2;
} else if (operation === "divide") {
if (num2 !== 0) {
result = num1 / num2;
} else {
alert("Division by zero is not allowed!");
return;
}
}
// Display the result
[Link]("result").innerText = ‘Result: ${result}’;
}
function performSquare() {
// Get the first input value
const num1 = parseFloat([Link]("num1").value);
// Calculate the square
const result = num1 * num1;
// Display the result
[Link]("result").innerText = ‘Result (Square): ${result}’;
}
</script>
</body>
</html>

Q.9) List and explain various popular windows events?


Ans). Here is a list of popular window events, along with explanations:
1. onload (Window Load Event)
• Description: The onload event occurs when the entire content of a window
(including images, scripts, and CSS) has been fully loaded.
• Usage: It’s typically used to initialize scripts or functions once the window
has finished loading, ensuring all elements are accessible and properly
rendered.
2. resize
• Description: The resize event is triggered when the size of the window
changes (either by resizing the window manually or programmatically).
• Usage: It’s commonly used for responsive design or when an application
needs to adjust elements dynamically based on the window size.
In programming, particularly with graphical user interfaces (GUIs), window events
are actions or occurrences that happen during the lifecycle of a window. These
events are typically triggered by user interactions (like clicking or resizing) or
system-level actions (like window focus change). Event handling is crucial for
creating responsive applications, and various frameworks (like JavaScript for web
applications, or WinForms and WPF for Windows applications) make use of these
events.
Here is a list of popular window events, along with explanations:

1. onload (Window Load Event)


• Description: The onload event occurs when the entire content of a window
(including images, scripts, and CSS) has been fully loaded.
• Usage: It’s typically used to initialize scripts or functions once the window
has finished loading, ensuring all elements are accessible and properly
rendered.
• Example:
javascript
Copy code
[Link] = function() {
[Link]("Window has fully loaded!");
};

2. resize
• Description: The resize event is triggered when the size of the window
changes (either by resizing the window manually or programmatically).
• Usage: It’s commonly used for responsive design or when an application
needs to adjust elements dynamically based on the window size.
• Example:
javascript
Copy code
[Link] = function() {
[Link]("Window size has changed!");
};

3. focus
• Description: The focus event occurs when the window or a specific element
(like an input field) gains focus, typically when clicked or tabbed into.
• Usage: It’s used for input handling or changing the appearance of elements
when they receive focus.

Q.10) What is frame and explain the HTML tags to create frames and how to
change the properties of the frame.
Ans). - Frames often confuse developers because they are technically separate
windows within the browser window.
- A frame can be manipulated as a window object, and JavaScript provides specific
methods for working with frames.
1. Manipulating Frames:
- Each frame in the browser window is accessible through ‘[Link][]’. This
array contains references to each individual frame object in the window.
2. Useful Properties for Frames:
- ‘frames[]’: Array of all frame objects in the current window.
- ‘[Link]’: The number of frames in the current window.
- ‘frames[name]’: A reference to a frame by its name.
- ‘parent’: A reference to the parent window of the frame.
- ‘self’: A reference to the current window (or frame).
- ‘top’: A reference to the top-most window (in a multi-level frame structure).
Example of a frameset with multiple frames:
<!DOCTYPE html>
<html>
<head>
<title>FrameSet Test</title>
</head>
<frameset rows="33%, *, 33%">
<frame src="[Link]" name="frame1" id="frame1" />
<frame src="[Link]" name="frame2" id="frame2" />
<frame src="[Link]" name="frame3" id="frame3" />
</frameset>
</html>
Q.11) Create a student information form to accept information like Name
Address, City. State, Gender, Mobile Number, and email id. Perform validations
for
i. Correct Names
ii. Mobile Names
iii. Email LD
Ans).
Program Code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Student Information Form</title>
<style>
body {
font-family: Arial, sans-serif;
margin: 20px;
padding: 0;
}
h1 {
text-align: center;
color: #333;
}
form {
width: 50%;
margin: 0 auto;
padding: 20px;
border: 1px solid #ccc;
border-radius: 10px;
box-shadow: 2px 2px 10px rgba(0, 0, 0, 0.1);
}
label {
display: block;
margin-bottom: 5px;
font-weight: bold;
}
input, select {
width: 100%;
padding: 10px;
margin-bottom: 15px;
border: 1px solid #ccc;
border-radius: 5px;
}
.gender {
width: auto;
margin-right: 10px;
}
button {
background-color: #007BFF;
color: white;
padding: 10px 20px;
border: none;
border-radius: 5px;
font-size: 16px;
cursor: pointer;
}
button:hover {
background-color: #0056b3;
}
.error {
color: red;
font-size: 14px;
}
</style>
</head>
<body>
<h1>Student Information Form</h1>
<form id="studentForm" validateForm()">
<label for="name">Name:</label>
<input type="text" id="name" placeholder="Enter your name">
<label for="address">Address:</label>
<input type="text" id="address" placeholder="Enter your address">
<label for="city">City:</label>
<input type="text" id="city" placeholder="Enter your city">
<label for="state">State:</label>
<input type="text" id="state" placeholder="Enter your state">
<label>Gender:</label>
<input type="radio" id="male" name="gender" value="Male" class="gender">
Male
<input type="radio" id="female" name="gender" value="Female" class="gender">
Female
<label for="mobile">Mobile Number:</label>
<input type="text" id="mobile" placeholder="Enter your mobile number">
<label for="email">Email ID:</label>
<input type="email" id="email" placeholder="Enter your email address">
<button type="submit">Submit</button>
</form>
<script>
// Function to validate form inputs
function validateForm() {
// Get form inputs
const name = [Link]("name").[Link]();
const mobile = [Link]("mobile").[Link]();
const email = [Link]("email").[Link]();
// Name validation: only letters
const nameRegex = /^[A-Za-z\s]+$/;
if (![Link](name)) {
alert("Name must contain only letters.");
return false;
}
// Mobile number validation: exactly 10 digits
const mobileRegex = /^\d{10}$/;
if (![Link](mobile)) {
alert("Mobile number must contain exactly 10 digits.");
return false;
}
// Email validation: correct format
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
if (![Link](email)) {
alert("Please enter a valid email address.");
return false;
}
alert("Form submitted successfully!");
return true;
}
</script>
</body>
</html>

1. Initial View:
- A form with fields for Name, Address, City, State, Gender, Mobile Number, and
Email ID appears.
2. Validations:
- Entering invalid inputs (e.g., numbers in the name, less than 10 digits for mobile,
or an incorrect email format) triggers appropriate error messages.
3. Successful Submission:
- Displays "Form submitted successfully!" if all inputs are valid.

You might also like