Java Script Imp
Java Script Imp
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.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.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.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.
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.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.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).
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.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]()’.
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>
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 () {
alert("Name must contain only letters.");
return false;
}
// Mobile number validation: exactly 10 digits
const mobileRegex = /^\d{10}$/;
if () {
alert("Mobile number must contain exactly 10 digits.");
return false;
}
// Email validation: correct format
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
if () {
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.