0% found this document useful (0 votes)
11 views110 pages

Full Stack Development Lab Manual

The document is a lab manual for a Full Stack Development course, detailing a series of experiments and programming tasks related to HTML, CSS, and JavaScript. It includes instructions for creating lists, tables, forms, and frames, as well as applying CSS styles and JavaScript functionalities. Each section contains specific programming assignments aimed at teaching students the fundamentals of web development.

Uploaded by

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

Full Stack Development Lab Manual

The document is a lab manual for a Full Stack Development course, detailing a series of experiments and programming tasks related to HTML, CSS, and JavaScript. It includes instructions for creating lists, tables, forms, and frames, as well as applying CSS styles and JavaScript functionalities. Each section contains specific programming assignments aimed at teaching students the fundamentals of web development.

Uploaded by

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

DEPARTMENT OF COMPUTER

SCIENCE & ENGINEERING


II. B. Tech II Semester
Full Stack Development –I
(23CS401S)

Lab Manual
Sl. No List of Experiments Page no
1 Lists, Links and Images 4
(a) Write a HTML program, to explain the working of lists.
Note: It should have an ordered list, unordered list, nested
lists and ordered list in an unordered list and definition lists.
(b) Write a HTML program, to explain the working of
hyperlinks using tag and href, target Attributes.
(c) Create a HTML document that has your image and your
friend’s image with a specific height and width. Also when
clicked on the images it should navigate to their respective
profiles.
(d) Write a HTML program, in such a way that, rather than
placing large images on a page, the preferred technique is to
use thumbnails by setting the height and width parameters to
something like to 100*100 pixels. Each thumbnail image is
also a link to a full sized version of the image. Create an
image gallery using this technique.
2 HTML Tables, Forms and Frames 13
(a) Write a HTML program, to explain the working of tables.
(b) Write a HTML program, to explain the working of tables by
preparing a timetable.
(c) Write a HTML program, to explain the working of forms by
designing Registration form.
(d) Write a HTML program, to explain the working of frames,
such that page is to be divided into 3 parts on either
direction.
3 HTML 5 and Cascading Style Sheets, Types of CSS 20
(a) Write a HTML program, that makes use of <article>,<aside>,
<figure>, <figcaption>, <footer>, <header>, <main>, <nav>,
<section>, <div>, <span> tags.
(b) Write a HTML program, to embed audio and video into
HTML web page.
(c) Write a program to apply different types (or levels of styles
or style specification formats) - inline, internal, external
styles to HTML elements. (identify selector, property and
value).

4 Selector forms 38
(a) Write a program to apply different types of selector forms
(i) Simple selector (element, id, class, group, universal)
(ii) Combinator selector (descendant, child, adjacent
sibling, general sibling)
(iii) Pseudo-class selector
(iv) Pseudo-element selector
(v) Attribute selector
5 CSS with Color, Background, Font, Text and CSS Box Model 52
(a) Write a program to demonstrate the various ways you can
reference a color in CSS.
(b) Write a CSS rule that places a background image halfway
down the page, tilting it horizontally. The image should
remain in place when the user scrolls up or down.
(c) Write a program using the following terms related to CSS
font and text: i. font-size ii. font-weight iii. font-style
(d) Write a program, to explain the importance of CSS Box
model using [Link] ii. Border iii. Margin iv. padding
6 Applying JavaScript - internal and external, I/O, Type Conversion 61
(a) Write a program to embed internal and external JavaScript in
a web page.
(b) Write a program to explain the different ways for displaying
output.
(c) Write a program to explain the different ways for taking input.
(d) Create a webpage which uses prompt dialogue box to ask a
voter for his name and age. Display the information in table
format along with either the voter can vote or not.
7 Java Script Pre-defined and User-defined Objects
a. Write a program using document object properties and
methods.
b. Write a program using window object properties and methods.
c. Write a program using array object properties and methods.
d. Write a program using math object properties and methods.
e. Write a program using string object properties and methods.
f. Write a program using regex object properties and methods.
g. Write a program using date object properties and methods.
h. Write a program to explain user-defined object by using
properties, methods, accessors, constructors and display.
8 Java Script Conditional Statements and Loops
a. Write a program which asks the user to enter three integers,
obtains the numbers from the user and outputs HTML text that
displays the larger number followed by the words “LARGER
NUMBER” in an information message dialog. If the numbers
are equal, output HTML text as “EQUAL NUMBERS”.
b. Write a program to display week days using switch case.
c. Write a program to print 1 to 10 numbers using for, while and
do-while loops.
d. Write aprogram to print data in object using for-in, for-each
and for-of loops
e. Develop a program to determine whether a given number is an
‘ARMSTRONG NUMBER’ or not. [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]
f. Write a program to display the denomination of the amount
deposited in the bank in terms of 100’s, 50’s, 20’s, 10’s, 5’s,
2’s & 1’s.
9 Java Script Functions and Events
a. Design a appropriate function should be called to display
[Link] of that number
ii. Fibonacci series up to that number
iii. Prime numbers up to that number
iv. Is it palindrome or not
b. Design a HTML having a text box and four buttons named
Factorial, Fibonacci, Prime, and Palindrome. When a button is
pressed an appropriate function should be called to display
[Link] of that number
ii. Fibonacci series up to that number
iii. Prime numbers up to that number
iv. Is it palindrome or not
c. Write a program to validate the following fields in a registration
page
i. Name (start with alphabet and followed by alphanumeric
and the length should not be less than 6 characters)
ii. Mobile (only numbers and length 10 digits)
iii. E-mail (should contain format like
xxxxxxx@[Link])
Basic of HTML, CSS and Java Script
HTML: HTML stands for Hyper Text Markup Language. HTML is use for creating web
page. It describes the structure of a web page. It consists of a series of tags.
HTML Tags: HTML Tags is a keyword that tells a web browser how to format and display
content on a web page.

Structure of a HTML web page

<html>
<head>
<tiltle> Page title </html>
</head>
<body>
<h1> It is used for heading </h1>
<p> It is used for paragraph </p>
</body>
</html>
Experiment 1
Lists, Links and Images
(a) Write a HTML program, to explain the working of lists. Note: It should have an
ordered list, unordered list, nested lists and ordered list in an unordered list and
definition lists.
(b) Write a HTML program, to explain the working of hyperlinks using tag and href,
target Attributes.
(c) Create a HTML document that has your image and your friend’s image with a
specific height and width. Also when clicked on the images it should navigate to
their respective profiles.
(d) Write a HTML program, in such a way that, rather than placing large images on a
page, the preferred technique is to use thumbnails by setting the height and width
parameters to something like to 100*100 pixels. Each thumbnail image is also a link
to a full sized version of the image. Create an image gallery using this technique.
Solution
(a) Write a HTML program, to explain the working of lists
List: A list in HTML is a way to group items together using tags. List is of 3 types.
 Ordered list.
 Unordered list.
 Description list.
HTML List tag
[Link] Name of the Tag Representation of Description about Tag
tag
1 Unordered List <ul> Defines unordered list.
2 Ordered List <ol> Defines Ordered list.
3 List Item <li> It defines the list item in a
list.
4 Description list <dl> It defines a description list.
5 Description term <dt> It defines a term or name in a
description list.
6 Description Defination <dd> It describes each term in a
description list.

Source code for unordered list


<html>
<body>

<h2>An unordered HTML list</h2>


<ul>
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li>
</ul>

</body>
</html>

Output

Source code for ordered list


<html>
<body>

<h2>An ordered HTML list</h2>

<ol>
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li>
</ol>

</body>
</html>

Output

Source code for Description list


<html>
<body>

<h2>A Description List</h2>


<dl>
<dt>Coffee</dt>
<dd>- black hot drink</dd>
<dt>Milk</dt>
<dd>- white cold drink</dd>
</dl>

</body>
</html>
Output

(b) Write a HTML program, to explain the working of hyperlinks using tag and href,
target Attributes.

Solution
Hyperlink: It is a link which help us to refer to a web page or another document. By
default a unvisited link is underlined and blue in color. A visited link is underlined and
purple in color. An active link is underlined and red in color.
HTML Links and the target attribute
 _self: It opens the document in a same window as it is clicked.
 _blank: It opens the document in a new window as it is clicked.
 _parent: It opens the document in a parent frame.
 _top: It opens the document in a full body of the window.
Absolute URLS: In absolute urls full url needs to be defined.
For e.g: < a href=[Link]/cse> CSE </a>
Relative URLs: in Relative urls a portion of url needs to be defined.
For e,g: <a href=”/cse”> CSE </a>

Source Code
<html>
<body>

<h2>Absolute URLs</h2>
<p><a href="[Link] target="_blank">W3C</a></p>
<p><a href="[Link] target="_blank">Google</a></p>

<h2>Relative URLs</h2>
<p><a href="html_images.asp">HTML Images</a></p>
<p><a href="/css/[Link]">CSS Tutorial</a></p>

</body>
</html>
Output

(c) Create a HTML document that has your image and your friend’s image with a specific
height and width. Also when clicked on the images it should navigate to their
respective profiles.
<img>: img tag is used for defining image in HTML.
<src>: It is used for source/ path of image file in HTML.
<alt>: It is used for alternate text of image in HTML.

Source Code
html>
<body>

<h2>Image as a Link</h2>

<p>The image is a link. You can click on it.</p>

<a href="[Link]">
<img src="[Link]" alt="HTML tutorial" style="width:42px;height:42px;">
</a>

</body>
</html>

Output

(d) Write a HTML program, in such a way that, rather than placing large images on a
page, the preferred technique is to use thumbnails by setting the height and width
parameters to something like to 100*100 pixels. Each thumbnail image is also a link
to a full sized version of the image. Create an image gallery using this technique.

Source Code
html>
<body>

<h2>Image as a Link</h2>

<p>The image is a link. You can click on it.</p>

<a href="[Link]">
<img src="[Link]" alt="HTML tutorial" style="width:100px;height:100px;">
</a>

</body>
</html>
Output
Experiment 2
HTML Tables, Forms and Frames
(a) Write a HTML program, to explain the working of tables.
(b) Write a HTML program, to explain the working of tables by preparing a timetable.
(c) Write a HTML program, to explain the working of forms by designing Registration
form.
(d) Write a HTML program, to explain the working of frames, such that page is to be
divided into 3 parts on either direction.

(a) Aim: Write a HTML program, to explain the working of tables.

HTML Table: A table in HTML consist of table cells inside rows and collmns. Table is
defined by <table> tag.
e.g: <table>
</table>
HTML Table tags
[Link] Name of the Tag Description of the Tag
1 <table> Defines a table.
2 <th> Defines a header cell in a table.
3 <tr> Defines a row in a table.
4 <td> Define a cell in a table.
5 <caption> Define a table caption.
6 <colgroup> Specify a group of one or more column in a table for
formatting.
7 <col> Specifies column properties for each column within a
<colgroup> element.
8 <thead> Groups the header content in a table.
9 <tbody> Groups the body content in a table.
10 <tfoot> Groups the footer content in a table.

Important Table properties


 Border: It is used for make border of each cell in a table. In HTML, various types of
table border possible, as per the requirement of table, choose the table border style.
Different types of table border
1. Solid table border.
2. Dotted table border.
3. Collapsed table border.
4. Rounded table border.
 Colspan: It is used to merge columns in a table.
 Rowspan: It is used to merge rows in a table.
Program of a table in HTML
<html>
<body>

<h2>Table in HTML</h2>

<table border="solid">
<tr>
<td>Emil</td>
<td>Tobias</td>
<td>Linus</td>
</tr>
</table>

</body>
</html>

Output

(b) Aim: Write a HTML program, to explain the working of tables by preparing a
timetable.

<html>
<head>
<title> II [Link] II Sem CSE C Class Time table </title>
</head>
<body>
<table border="solid">
<tr>
<th colspan="9"> Academic Year: 2024-2025 II [Link] II Sem
CSE C Room No: G11</th>
</tr>
<tr>
<td rowspan="2"> Days</td><td> 9:00 AM - 10:00
AM</td><td> 10:00 AM - 11:00 AM</td><td> 11:00 AM - 12:00 PM</td><td> 12:00 PM -
12:30 PM</td><td> 12:30 PM - 1:30 PM</td><td> 1:30 PM - 2:20 PM</td><td> 2:20 PM -
3:10 PM</td><td> 3:10 PM - 4:00 PM</td>
<tr>
<td>1</td><td>2</td><td>3</td><td rowspan="7"> LUNCH
BREAK</td><td>4</td><td>5</td><td>6</td><td>7</td>
</tr>
</tr>
<tr>
<td> Monday</td><td> SE </td><td> P&S </td><td> DBMS
</td><td> OS </td><td> P&S </td><td> MEFA </td><td> DBMS </td>
</tr>
<tr>
<td> Tuesday</td><td> OS </td><td> DBMS </td><td>
MEFA </td><td> SE </td><td colspan="3"> Database Management System Laboratory
</td>
</tr>
<tr>
<td> Wednesday</td><td> SE </td><td> P&S </td><td>
DBMS </td><td> SS </td><td> OS </td><td> APT </td><td> DBMS </td>
</tr>
<tr>
<td> Thursday</td><td colspan="3"> Full stack Development -
I Laboratory</td><td> P&S </td><td> MEFA </td><td> SE </td><td> OS </td>
</tr>
<tr>
<td> Friday</td><td colspan="3"> Design Thinking &
Innovation </td><td> TECH C </td><td> DBMS </td><td> MEFA </td><td> SE </td>
</tr>
<tr>
<td> Saturday</td><td> P&S </td><td> MEFA </td><td> OS
</td><td> SE </td><td colspan="3"> Operating System Laboratory </td>
</tr>

</table>
</body>
</html>

Output

(c) Aim: Write a HTML program, to explain the working of forms by designing Registration
form.
Form in HTML: Form is used to collect user input. The user input is most often sent to a
server for processing like storing, analysing etc.
HTML Form tags
[Link] Name of the Tag Description of the Tag
1 <input type="text"> Displays a single-line text input field.
2 <input type="radio"> Display a radio button (for selecting one of many
choice).
3 <input type="checkbox"> Displays a checkbox (for selecting zero or more of
many choices).
4 <input type="submit"> Displays a submit button (for submitting the form).
5 <input type="button"> Displays a clickable button.

Program for HTML Form


<html>
<body>

<h2>Form In HTML</h2>
<form>
<label for="fname">First name:</label><br>
<input type="text" id="fname" name="fname" ><br>
<label for="lname">Last name:</label><br>
<input type="text" id="lname" name="lname">
<br><br>
<input type="submit" id="sbutton" name="sbutton">
</form>
</body>
</html>

Output
(d) Write a HTML program, to explain the working of frames, such that page is to be
divided into 3 parts on either direction.

Programs of <fame> tag


<html>
<head>
<title>HTML Frames</title>
</head>
<frameset rows="10%,80%,10%">
<frame name="top" src="[Link] />
<frame name="main" src="[Link] />
<frame name="bottom" src="[Link] />
<noframes>
<body>
Your browser does not support frames.
</body>
</noframes>
</frameset>
</html>
Output of <frame>tag
Experiment 3
HTML 5 and Cascading Style Sheets, Types of CSS
(a) Write a HTML program, that makes use of <article>,<aside>, <figure>,
<figcaption>, <footer>, <header>, <main>, <nav>, <section>, <div>, <span> tags.
(b) Write a HTML program, to embed audio and video into HTML web page.
(c) Write a program to apply different types (or levels of styles or style specification
formats) - inline, internal, external styles to HTML elements. (identify selector,
property and value).

(a) Aim: Write a HTML program, that makes use of <article>,<aside>, <figure>,
<figcaption>, <footer>, <header>, <main>, <nav>, <section>, <div>, <span> tags.
<article> tag: Article tag in HTML represent a self-contained composition in a
document, page, application, site which is intended to be independently reuseable.
Program of article tag
<html>
<head>
<title> Syntax of article tag</title>
</head>
<body>
<article>
<h1> Writing article tag</h1>
<p>
It is an article tag.
</p>
</article>
</body>
</html>
Output

<aside> tag: Aside tag is a semantic element introduced to markup content that is indirectly
related to the main article content of a page.
Program for aside tag
<!DOCTYPE html>
<html>
<head>
<title> Syntax for aside tag</title>
</head>
<body>
<aside>
<h1> Writing aside tag</h1>
<p>
It is an aside tag.
</p>
</aside>
</body>
</html>

Output
<figure> tag: Figure tag in HTML specifies self-contained content like illustrations, diagram,
photos, code listings etc.
Program of figure tag
<html>
<head>
<title> Usage of Figure tag</title>
</head>
<body>

<h1>Figure tag</h1>
<figure>
<img src="pic_trulli.jpg" alt="Trulli" style="width:100%">
</figure>
</body>
</html>

Output
<figcaption> tag: Figcaption in HTML defines a caption for a <figure> element.
Program of <figcaption> tag
<html>
<head>
<title> Usage of Figure and Figcaption</title>
</head>
<body>

<h1>The figure and figcaption elements</h1>

<figure>
<img src="pic_trulli.jpg" alt="Trulli" style="width:100%">
<figcaption>Fig.1 - Trulli, Puglia, Italy</figcaption>
</figure>
</body>
</html>
Output

<footer> tag: Footer tag in HTML is a structural element used to identify the footer of a
page, document, article or section.
Program of footer tag
<html>
<head>
<title> Footer section in HTML</title>
</head>
<body>
<footer>
It is footer section of the page
</footer>
</body>
</html>

Output

<header> tag: Header tag in HTML represents a container for introductory content or s set
of navigational links.
Program of header tag
<html>
<body>

<header>
<h1>A heading here</h1>
</header>

</body>
</html>
Output

<main> tag: Main tag in HTML is a structural element that represent the main content of a
web page.

Program of <main> tag


<html>
<head>
<title> Use of Main tag</title>
</head>
<body>
<main>
<h1> It is a main tag</h1>
</main>
</body>
</html>

Output

<nav> tag: The nav element represents a section of a page that links to other pages or to
parts within the page.

Program of <nav> tag


<html>
<body>

<h1>The nav element</h1>

<p>The nav element defines a set of navigation links:</p>

<nav>
<a href="/html/">HTML</a> |
<a href="/css/">CSS</a> |
<a href="/js/">JavaScript</a> |
<a href="/python/">Python</a>
</nav>

</body>
</html>

Output

<section> tag: Section in HTML is a structural HTML element used to group together related
elements.
Program of <section> tag
<html>
<body>

<h1>The section element</h1>


<section>
<h2>WWF History</h2>
<p>The World Wide Fund for Nature (WWF) is an international organization working on
issues regarding the conservation, research and restoration of the environment, formerly
named the World Wildlife Fund. WWF was founded in 1961.</p>
</section>

<section>
<h2>WWF's Symbol</h2>
<p>The Panda has become the symbol of WWF. The well-known panda logo of WWF
originated from a panda named Chi Chi that was transferred from the Beijing Zoo to the
London Zoo in the same year of the establishment of WWF.</p>
</section>

</body>
</html>

Output

<div> tag: The HTML <div> tag is a block level element that groups content on a webpage.

Program of <div> tag


<html>
<head>
<title> Div Tag</title>
</head>
<body>

<h1>The div element</h1>

<div>
<h2>This is a heading in a div element</h2>
<p>This is some text in a div element.</p>
</div>

</body>
</html>

Output

<span> tag: The span tag is a inline container used to mark up a mark up a part of a text or a
part of document.

Program of <span> tag


<html>
<body>
<h1>The span element</h1>
<p>My mother has <span style="color:blue;font-weight:bold">blue</span> eyes and my
father has <span style="color:darkolivegreen;font-weight:bold">dark green</span>
eyes.</p>
</body>
</html>

Output

(b) Aim: Write a HTML program, to embed audio and video into HTML web page.
<audio> tag: The <audio> tag is used to emend sound content in a document, such as music
or other audio stream. There are three types of audio format supported in the HTML tag:
MP3, WAV, OGG.

Audio Attributes in audio tag


S.n Attribute Value Description
o
1 autoplay autoplay Specifies that the audio will start playing as soon
as it is ready
2 controls controls Specifies that audio controls should be displayed
(such as a play/pause button etc)
3 loop loop Specifies that the audio will start over again,
every time it is finished
4 muted muted Specifies that the audio output should be muted
5 preload auto Specifies if and how the author thinks the audio
metadata should be loaded when the page loads
none
6 src URL Specifies the URL of the audio file

<video> tag: The <video> tag is used to embed video content in a document, such as a
movie clip or other video streams. There are three types of video format supported in the
HTML tag: MP3, WAV, OGG.
Video Attributes in Video tag
[Link] Attribute Value Description
1 autoplay autoplay Specifies that the video will start
playing as soon as it is ready
2 controls controls Specifies that video controls should be
displayed (such as a play/pause button
etc).
3 height pixels Sets the height of the video player
4 loop loop Specifies that the video will start over
again, every time it is finished
5 muted muted Specifies that the audio output of the
video should be muted
6 poster URL Specifies an image to be shown while
the video is downloading, or until the
user hits the play button
7 preload auto Specifies if and how the author thinks
metadata the video should be loaded when the
none page loads
8 src URL Specifies the URL of the video file
9 width pixels Sets the width of the video player

Program of <audio> and <video> tag


<html>
<head>
<title> Audio and Video in a web page</title>
</head>
<body>

<h1>Audio and Video in a web page</h1>

<p>Click on the play button to play a audio or video</p>

<audio controls>
<source src="[Link]" type="audio/ogg">

</audio>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
<video width="200px" height="200px" controls>
<source src="movie.mp4" type="video/mp4">

</video>

</body>
</html>

Output

c) Write a program to apply different types (or levels of styles or style specification
formats) - inline, internal, external styles to HTML elements. (identify selector,
property and value).
CSS (Cascading Style Sheet) describes the HTML elements which are displayed
on screen, paper, or in other media. It saves a lot of time. It controls the layout of
multiple web pages at one time. It sets the font-size, font-family, color, background
color on the page.
There are 3 types of CSS which are below:
o Inline CSS
o Internal/ Embedded CSS
o External CSS
1. Internal CSS
The Internal CSS has <style> tag in the <head> section of the HTML document. This
CSS style is an effective way to style single pages. Using the CSS style for multiple web
pages is time-consuming because we require placing the style on each web page.
We can use the internal CSS by using the following steps:
1. Firstly, open the HTML page and locate the <head>
2. Put the following code after the <head>
3. Add the rules of CSS in the new line.
4. Close the style tag.

Pros of Internal CSS


o Internal CSS cannot upload multiple files when we add the code with the HTML
page.
Cons of Internal CSS:
o Adding code in the HTML document will reduce the page size and loading time of
the webpage.

Program of internal CSS


<!DOCTYPE html>
<html>
<head>
<style>
body {
background-color: black;
}
h1 {
color: red;
padding: 50px;
}
</style>
</head>
<body>
<h2>CSS types</h2>
<p>Cascading Style sheet types: inline, external and internal</p>
</body>
</html>

2. External CSS
In external CSS, we link the web pages to the external .css file. It is created by text
editor. The CSS is more efficient method for styling a website. By editing the .css file,
we can change the whole site at once.
To use the external CSS, follow the steps, given below:
1. Create a new .css file with text editor, and add Cascading Style Sheet rules
too.
2. Add a reference to the external .cssfile right after <title> tag in
the <head> section of HTML sheet
Pros of External CSS:
o Our files have a cleaner structure and smaller in size.
o We use the same .css file for multiple web pages in external CSS.
Cons of External CSS:
o The pages cannot be delivered correctly before the external CSS is loaded.
o In External CSS, uploading many CSS files can increase the download time of a
website.
Program of external CSS
HTML Page Code
<html>

<head>
<link rel="stylesheet" href="[Link]" />
</head>

<body>
<div class="main">
<h1 class="G">
This is h1 tag
</h1>
<p id="g">
A computer science portal for geeks
</p>
</div>
</body>

</html>

CSS page code named as [Link]


.main {
text-align: center;
}

.G {
font-size: 60px;
color: green;
}
#g {
font-size: 25px;
color: skyblue;
};
3. Inline CSS
Inline CSS is used to style a specific HTML element. Add a style attribute to each HTML
tag without using the selectors. Managing a website may difficult if we use only inline
CSS. However, Inline CSS in HTML is useful in some situations. We have not access
the CSS files or to apply styles to element.
Pros of inline CSS:
o We can create CSS rules on the HTML page.
o We cannot create and upload a separate document in inline CSS.
Cons of inline CSS:
o Inline CSS, adding CSS rules to HTML elements is time-consuming and messes up
the HTML structure.
o It styles multiple elements at the same time which can affect the page size and
download time of the page.

Program of Inline CSS


<html>

<head>
<style>
body {
background-color: #e0e0e0;
font-family: 'Courier New', Courier, monospace;
}

h2 {
color: #09912b;
text-align: left;
}

p{
font-size: 16px;
color: #0a0a0a;
}
</style>
<title>Internal CSS Example</title>
</head>

<body>
<h2>Internal CSS Demo </h2>
<p>
This paragraph is styled using internal CSS.
The styles are defined within the
&lt;style&gt; tag inside the HTML document.
</p>
</body>

</html>
Experiment 4
Aim: Selector forms
Write a program to apply different types of selector forms
Simple selector (element, id, class, group, universal)
Combinator selector (descendant, child, adjacent sibling, general sibling)
Pseudo-class selector
Pseudo-element selector
Attribute selector

[Link] Types of CSS Selectors Description


1 It is used to select the HTML elements based
Simple Selectors
on their element name, id, attributes, etc
2 Universal Selector Selects all elements on the page.
3 Targets elements based on their attribute
Attribute Selector
values.
4 Selects elements based on their state or
Pseudo-Class Selector
position, such as :hover for hover effects.
5 Combine selectors to specify relationships
Combinator Selectors between elements, such as descendants ( ) or
child (>).
6 Selects specific parts of an element, such
Pseudo-Element Selector
as ::before or ::after.

Simple Selector
[Link] Types of Simple Selector Description of different types of Simple
Selector
1 Selects HTML elements based on their tag
Element Selector
names.
2 Targets an HTML element with a specific id
Id Selector
attribute.
3 Selects elements with a particular class
Class Selector
attribute.

Code for Element selector


<html>
<head>
<style>
p{
text-align: center;
color: blue;
}
</style>
</head>
<body>
<p>This style will be applied on every paragraph.</p>
<p id="para1">Me too!</p>
<p>And me!</p>
</body>
</html>

Output

Code for Id Selector


<html>
<head>
<style>
#para1 {
text-align: center;
color: blue;
}
</style>
</head>
<body>
<p id="para1">Hello</p>
<p>This paragraph will not be affected.</p>
</body>
</html>

Output

Code for Class selector


<html>
<head>
<style>
[Link] {
text-align: center;
color: blue;
}
</style>
</head>
<body>
<h1 class="center">This heading is not affected</h1>
<p class="center">This paragraph is blue and center-aligned.</p>
</body>
</html>

Ouput
CSS Combinators
There are four different types of CSS Combinators. These are:
 Descendant Combinator.
 Child Combinator.
 Next sibling Combinator
 Subsequent Sibling Combinator.

Descendant Combinator: The descendant combinator matches all the elements that are
descendants of a specified element.
Code for Descendant Combinator
<html>
<head>
<style>
div p {
background-color: yellow;
}
</style>
</head>
<body>

<h2>Descendant Selector</h2>

<p>The descendant selector matches all elements that are descendants of a specified
element.</p>

<div>
<p>Paragraph 1 in the div.</p>
<p>Paragraph 2 in the div.</p>
<section><p>Paragraph 3 in the div.</p></section>
</div>

<p>Paragraph 4. Not in a div.</p>


<p>Paragraph 5. Not in a div.</p>

</body>
</html>

Output

Child Combinator: The child combinator selects all elements that are the children of a
specified element.

Code for Child Combinator


<html>
<head>
<style>
div > p {
background-color: yellow;
}
</style>
</head>
<body>

<h2>Child Selector</h2>

<p>The child selector (>) selects all elements that are the children of a specified
element.</p>

<div>
<p>Paragraph 1 in the div.</p>
<p>Paragraph 2 in the div.</p>
<section>
<!-- not Child but Descendant -->
<p>Paragraph 3 in the div (inside a section element).</p>
</section>
<p>Paragraph 4 in the div.</p>
</div>

<p>Paragraph 5. Not in a div.</p>


<p>Paragraph 6. Not in a div.</p>

</body>
</html>

Output
Next Sibling Combinator: The next sibling combinator is used to select an element that is
directly after another specific element.
Code for next sibling combinator
<html>
<head>
<style>
div + p {
background-color: yellow;
}
</style>
</head>
<body>

<h2>Adjacent Sibling Selector</h2>

<p>The + selector is used to select an element that is directly after another specific
element.</p>
<p>The following example selects the first p element that are placed immediately after div
elements:</p>

<div>
<p>Paragraph 1 in the div.</p>
<p>Paragraph 2 in the div.</p>
</div>

<p>Paragraph 3. After a div.</p>


<p>Paragraph 4. After a div.</p>

<div>
<p>Paragraph 5 in the div.</p>
<p>Paragraph 6 in the div.</p>
</div>

<p>Paragraph 7. After a div.</p>


<p>Paragraph 8. After a div.</p>

</body>
</html>

Output
Subsequent- sibling Combinator: The subsequent-sibling combinator selects all elements
that are next siblings of a specified element.
Code for Subsequent – Sibling Combinator
<html>
<head>
<style>
div ~ p {
background-color: yellow;
}
</style>
</head>
<body>

<h2>General Sibling Selector</h2>

<p>The general sibling selector (~) selects all elements that are next siblings of a specified
element.</p>
<p>Paragraph 1.</p>

<div>
<p>Paragraph 2.</p>
</div>

<p>Paragraph 3.</p>
<code>Some code.</code>
<p>Paragraph 4.</p>

</body>
</html>

Output

CSS Pseudo Classes


Code for Pseudo classes
<html>
<head>
<style>
/* unvisited link */
a:link {
color: red;
}

/* visited link */
a:visited {
color: green;
}

/* mouse over link */


a:hover {
color: hotpink;
}

/* selected link */
a:active {
color: blue;
}
</style>
</head>
<body>

<h2>Styling a link depending on state</h2>

<p><b><a href="[Link]" target="_blank">This is a link</a></b></p>


<p><b>Note:</b> a:hover MUST come after a:link and a:visited in the CSS definition in
order to be effective.</p>
<p><b>Note:</b> a:active MUST come after a:hover in the CSS definition in order to be
effective.</p>
</body>
</html>

Output

Pseudo element
Code for Pseudo element
<html>
<head>
<style>
p::first-line {
color: #ff0000;
font-variant: small-caps;
}
</style>
</head>
<body>

<p>You can use the ::first-line pseudo-element to add a special effect to the first line of a text.
Some more text. And even more, and more, and more, and more, and more, and more, and
more, and more, and more, and more, and more, and more.</p>

</body>
</html>
Output

Attribute selector

Code for Attribute Selector


<html>
<head>
<style>
a[target] {
background-color: yellow;
}
</style>
</head>
<body>

<h2>CSS [attribute] Selector</h2>


<p>The links with a target attribute gets a yellow background:</p>

<a href="[Link]
<a href="[Link] target="_blank">[Link]</a>
<a href="[Link] target="_top">[Link]</a>

</body>
</html>
Output
Experiment 5
Aim: CSS with Color, Background, Font, Text and CSS Box Model
(a) Write a program to demonstrate the various ways you can reference a color in CSS.
(b) Write a CSS rule that places a background image halfway down the page, tilting it
horizontally. The image should remain in place when the user scrolls up or down.
(c) Write a program using the following terms related to CSS font and text: i. font-size ii.
font-weight iii. font-style
(d) Write a program, to explain the importance of CSS Box model using [Link] ii.
Border iii. Margin iv. padding

(a) Aim: Write a program to demonstrate the various ways you can reference a color in
CSS.
Source Code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CSS Color References</title>
<style>
body {
font-family: Arial, sans-serif;
}

.color-box {
width: 200px;
height: 100px;
margin: 10px;
display: inline-block;
text-align: center;
color: white;
line-height: 100px;
font-weight: bold;
}

.named-color {
background-color: red; /* Named color */
}

.hex-color {
background-color: #FF5733; /* Hexadecimal color */
}

.rgb-color {
background-color: rgb(255, 87, 51); /* RGB color */
}

.rgba-color {
background-color: rgba(255, 87, 51, 0.5); /* RGBA color */
}

.hsl-color {
background-color: hsl(9, 100%, 60%); /* HSL color */
}

.hsla-color {
background-color: hsla(9, 100%, 60%, 0.5); /* HSLA color */
}

.color-function {
background-color: rgb(100%, 50%, 30%); /* Color function (percentage) */
}
</style>
</head>
<body>

<div class="color-box named-color">Named Color</div>


<div class="color-box hex-color">Hex Color</div>
<div class="color-box rgb-color">RGB Color</div>
<div class="color-box rgba-color">RGBA Color</div>
<div class="color-box hsl-color">HSL Color</div>
<div class="color-box hsla-color">HSLA Color</div>
<div class="color-box color-function">Color Function</div>

</body>
</html>

Output

(b) Aim: Write a CSS rule that places a background image halfway down the page,
tilting it horizontally. The image should remain in place when the user scrolls up or
down.

Source Code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Fixed Background Image</title>
<style>
/* Apply the background image to the entire HTML document */
html {
height: 100%; /* Ensures the HTML takes full height */
}

body {
background-image: url(''); /* Set your image URL here */
background-position: center 50%; /* Positions the image horizontally centered and
vertically halfway */
background-size: cover; /* Ensures the image covers the whole viewport */
background-attachment: fixed; /* Keeps the image fixed when scrolling */
transform: rotate(45deg); /* Tilts the image horizontally */
height: 100%; /* Ensures body takes full height */
margin: 0; /* Removes default margin */
}

/* Optionally, style the content to create some scrollable content */


.content {
height: 200vh; /* Make the page scrollable */
padding: 20px;
color: white;
}
</style>
</head>
<body>

<div class="content">
<h1>Fixed Background with Tilt</h1>
<p>This background stays in place even as you scroll. The image is centered horizontally
and tilted.</p>
</div>

</body>
</html>

(c) Aim: Write a program using the following terms related to CSS font and text:
i. font-size ii. font-weight iii. font-style

Source Code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CSS Font and Text Styling</title>
<style>
/* Styling for the heading */
h1 {
font-size: 36px; /* Set the font size to 36px */
font-weight: bold; /* Make the font bold */
font-style: italic; /* Apply italic style to the text */
color: #2c3e50; /* Set the color of the text */
text-align: center; /* Center align the text */
margin-top: 50px; /* Add space above the heading */
}

/* Styling for the paragraph */


p{
font-size: 18px; /* Set the font size to 18px */
font-weight: normal; /* Set the font weight to normal (default) */
font-style: normal; /* Set the font style to normal (default) */
color: #34495e; /* Set the color of the text */
line-height: 1.6; /* Set line height for better readability */
margin: 20px; /* Add some space around the paragraph */
}

/* Add some styling for the subheading */


h2 {
font-size: 24px; /* Set the font size to 24px */
font-weight: lighter; /* Set the font weight to lighter */
font-style: oblique; /* Set the font style to oblique */
color: #e74c3c; /* Set the color of the text */
text-align: left; /* Align the text to the left */
margin-top: 30px; /* Add space above the subheading */
}
</style>
</head>
<body>

<h1>This is a Styled Heading</h1>

<p>This is a paragraph of text. The font size is set to 18px, and the font weight is normal.
The text style is also normal, which is the default.</p>

<h2>This is a Subheading with a Different Style</h2>


<p>Here's another paragraph. You can see the difference in font size, weight, and style
between the heading and the paragraph. Notice that the subheading is lighter and uses an
oblique style.</p>
</body>
</html>

Output

(d) Aim: Write a program, to explain the importance of CSS Box model using
i. Content ii. Border iii. Margin iv. padding

Source Code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CSS Box Model</title>
<style>
/* Styling the box element to demonstrate the box model */
.box {
width: 300px; /* Set the width of the content area */
height: 200px; /* Set the height of the content area */
background-color: lightblue; /* Set the background color of the content */

/* Adding padding (space between content and border) */


padding: 20px; /* 20px padding on all sides */
/* Adding a border */
border: 5px solid darkblue; /* 5px solid border with dark blue color */

/* Adding margin (space outside the border) */


margin: 30px; /* 30px margin on all sides */

/* Centering the text */


text-align: center;
line-height: 160px; /* Vertically centering the text inside the box */
font-size: 20px; /* Set the font size of the text */
}

/* Optional: Styling for the surrounding container */


.container {
display: flex;
justify-content: center;
align-items: center;
height: 100vh; /* Make the container take up the full height of the viewport */
background-color: #f0f0f0; /* Set a background color for the page */
}
</style>
</head>
<body>

<div class="container">
<!-- Box to demonstrate the CSS Box Model -->
<div class="box">
Box Model Example
</div>
</div>

</body>
</html>

Output
Experiment 6
Aim: Applying JavaScript - internal and external, I/O, Type Conversion
(a) Write a program to embed internal and external JavaScript in a web page.
(b) Write a program to explain the different ways for displaying output.
(c) Write a program to explain the different ways for taking input.
Create a webpage which uses prompt dialogue box to ask a voter for his name and age.
Display the information in table format along with either the voter can vote or not.

Solution
(a) Aim: Write a program to embed internal and external JavaScript in a web page.
Source Code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>JavaScript Example</title>

<!-- External JavaScript file -->


<script src="[Link]"></script>

<style>
body {
font-family: Arial, sans-serif;
text-align: center;
}
</style>
</head>
<body>
<h1>Embedding Internal and External JavaScript</h1>
<p id="message"></p>

<!-- Button to trigger internal JavaScript function -->


<button onclick="displayMessage()">Click me to display a message</button>

<!-- Internal JavaScript code -->


<script>
// Internal JavaScript to change the text content of the message
function displayMessage() {
[Link]("message").innerHTML = "Hello, this message is from
internal JavaScript!";
}
</script>

</body>
</html>

Java script file code


[Link] = function() {
[Link]("This message is from the external JavaScript file!");
};
(b)
Aim: Write a program to explain the different ways for displaying output
Source Code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Display Output Examples</title>
<style>
body {
font-family: Arial, sans-serif;
text-align: center;
margin-top: 30px;
}
</style>
</head>
<body>
<h1>Different Ways to Display Output in JavaScript</h1>

<!-- Buttons to trigger each output method -->


<button onclick="showAlert()">Alert Method</button>
<button onclick="writeToDocument()">Document Write Method</button>
<button onclick="logToConsole()">Console Log Method</button>
<button onclick="changeContent()">Change Content Method</button>

<hr>

<p id="content">This is the original content of the paragraph.</p>

<script>
// Method 1: Alert Method
function showAlert() {
alert("This is an alert message!"); // Pops up an alert box with the message
}

// Method 2: Document Write Method


function writeToDocument() {
[Link]("This is written using [Link](). <br>It overwrites the entire
document content!"); // Writes directly to the page
}

// Method 3: Console Log Method


function logToConsole() {
[Link]("This is logged to the console."); // Logs a message to the browser's
console
}

// Method 4: Change Content Method


function changeContent() {
[Link]("content").innerHTML = "The content of this paragraph
has been changed using JavaScript!";
}
</script>

</body>
</html>

C)
Aim: Write a program to explain the different ways for taking input.
Source Code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Taking Input in JavaScript</title>

<style>
body {
font-family: Arial, sans-serif;
text-align: center;
margin-top: 30px;
}
input, button {
margin-top: 10px;
padding: 10px;
font-size: 16px;
}
</style>
</head>
<body>
<h1>Different Ways to Take Input in JavaScript</h1>

<!-- Button for the Prompt Method -->


<button onclick="promptInput()">Enter your name using prompt()</button>
<p id="prompt-output"></p>

<hr>

<!-- HTML Input Method -->


<label for="html-input">Enter your favorite color:</label>
<input type="text" id="html-input" placeholder="Type color here">
<button onclick="htmlInput()">Submit</button>
<p id="html-input-output"></p>

<hr>

<!-- Event Listener Method -->


<label for="event-input">Enter your age:</label>
<input type="number" id="event-input" placeholder="Type age here">
<button id="submit-age">Submit Age</button>
<p id="event-output"></p>

<script>
// Method 1: Using prompt() to get input from the user
function promptInput() {
var name = prompt("Please enter your name:");
if (name != null) {
[Link]("prompt-output").innerHTML = "Hello, " + name + "!
You entered your name using prompt().";
}
}

// Method 2: Using HTML input elements


function htmlInput() {
var color = [Link]("html-input").value;
if (color) {
[Link]("html-input-output").innerHTML = "Your favorite color
is: " + color;
} else {
[Link]("html-input-output").innerHTML = "Please enter a
color.";
}
}

// Method 3: Using event listeners to get input


[Link]("submit-age").addEventListener("click", function() {
var age = [Link]("event-input").value;
if (age) {
[Link]("event-output").innerHTML = "You are " + age + "
years old.";
} else {
[Link]("event-output").innerHTML = "Please enter your age.";
}
});
</script>
</body>
</html>
Experiment 7
Java Script Pre-defined and User-defined Objects
a. Write a program using document object properties and methods.
b. Write a program using window object properties and methods.
c. Write a program using array object properties and methods.
d. Write a program using math object properties and methods.
e. Write a program using string object properties and methods.
f. Write a program using regex object properties and methods.
g. Write a program using date object properties and methods.
h. Write a program to explain user-defined object by using properties, methods,
accessors, constructors and display.

Solution
i. Aim: Write a program using document object properties and methods.

Source Code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document Object Example</title>
<style>
.text {
font-size: 20px;
color: black;
}
</style>
</head>
<body>
<h1 id="header">Welcome to the Document Object Example</h1>
<p id="text" class="text">This is a sample text. Click the button below to change
its content and style.</p>

<button onclick="changeContent()">Click Me to Change Content</button>

<script>
// Changing content using [Link]()
function changeContent() {
// Access the paragraph element
var paragraph = [Link]("text");

// Change the text content


[Link] = "The content has been changed!";

// Change the font color using the style property


[Link] = "blue";

// Change the font size


[Link] = "25px";

// Accessing and changing the heading content


var heading = [Link]("header");
[Link] = "Content and Style Updated!";
}
</script>
</body>
</html>

(ii) Aim: Write a program using window object properties and methods.

Source Code

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Window Object Example</title>
</head>
<body>
<h1>Window Object Methods and Properties</h1>

<button onclick="showAlert()">Show Alert</button>


<button onclick="openNewWindow()">Open New Window</button>
<button onclick="resizeWindow()">Resize Window</button>
<button onclick="showWindowProperties()">Show Window Properties</button>

<script>
// 1. Window Alert Example
function showAlert() {
[Link]("This is an alert using the window object!");
}

// 2. Open a new window using [Link]()


function openNewWindow() {
// Open a new window with a specific URL
[Link]("[Link] "_blank", "width=600, height=400");
}

// 3. Resize the current window using [Link]()


function resizeWindow() {
// Resize the current browser window to 800x600
[Link](800, 600);
}

// 4. Show current window properties using window properties


function showWindowProperties() {
// Displaying some window properties in the console
[Link]("Window Width: " + [Link]);
[Link]("Window Height: " + [Link]);
[Link]("Page URL: " + [Link]);
[Link]("Browser Name: " + [Link]);
}
</script>
</body>
</html>

(iii) Aim: Write a program using array object properties and methods.
Source Code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Array Object Methods and Properties</title>
</head>
<body>
<h1>Array Object Methods and Properties Example</h1>

<button onclick="addItem()">Add Item to Array</button>


<button onclick="removeItem()">Remove Last Item from Array</button>
<button onclick="shiftItem()">Remove First Item from Array</button>
<button onclick="unshiftItem()">Add Item to Beginning</button>
<button onclick="displayArray()">Display Array</button>
<button onclick="arrayLength()">Show Array Length</button>

<h3>Array Contents:</h3>
<ul id="arrayList"></ul>

<script>
// Initial array
let myArray = ["apple", "banana", "cherry"];

// Display the array on the web page


function displayArray() {
const listElement = [Link]("arrayList");
[Link] = ""; // Clear current list
[Link](item => {
const li = [Link]("li");
[Link] = item;
[Link](li);
});
}

// Add an item to the end of the array (push)


function addItem() {
[Link]("grape");
displayArray();
}

// Remove the last item from the array (pop)


function removeItem() {
[Link]();
displayArray();
}

// Remove the first item from the array (shift)


function shiftItem() {
[Link]();
displayArray();
}

// Add an item to the beginning of the array (unshift)


function unshiftItem() {
[Link]("kiwi");
displayArray();
}
// Show the current length
function arrayLength() {
alert("Array Length: " + [Link]);
}

// Initial display of the array


displayArray();
</script>
</body>
</html>

iv) Aim: Write a program using math object properties and methods.
Source Code
// Math Object Example Program

// Using [Link] to get the value of Pi


[Link]("Value of Pi:", [Link]);

// Using [Link]() to calculate the square root of a number


let num = 16;
[Link](`Square root of ${num}:`, [Link](num));

// Using [Link]() to calculate the power of a number


let base = 2;
let exponent = 3;
[Link](`${base} raised to the power of ${exponent}:`, [Link](base, exponent));

// Using [Link]() to generate a random number between 0 and 1


[Link]("Random number between 0 and 1:", [Link]());
// Using [Link]() to round a number down to the nearest integer
let decimalNum = 9.87;
[Link]("Rounded down value:", [Link](decimalNum));

// Using [Link]() to round a number up to the nearest integer


[Link]("Rounded up value:", [Link](decimalNum));

// Using [Link]() to round a number to the nearest integer


[Link]("Rounded to the nearest integer:", [Link](decimalNum));

// Using [Link]() to find the absolute value of a number


let negativeNum = -42;
[Link]("Absolute value of", negativeNum, "is:", [Link](negativeNum));

// Using [Link]() to find the largest value from a list of numbers


let largestNum = [Link](1, 5, 7, 20, 3);
[Link]("Largest number:", largestNum);

// Using [Link]() to find the smallest value from a list of numbers


let smallestNum = [Link](1, 5, 7, 20, 3);
[Link]("Smallest number:", smallestNum);

// Using [Link]() to calculate the sine of an angle in radians


let angle = [Link] / 2; // 90 degrees in radians
[Link]("Sine of 90 degrees:", [Link](angle));

// Using [Link]() to calculate the cosine of an angle in radians


[Link]("Cosine of 90 degrees:", [Link](angle));

// Using [Link]() to find the natural logarithm (base e) of a number


let value = 10;
[Link]("Natural logarithm of", value, ":", [Link](value));

// Using [Link]() to calculate e raised to the power of a number


let power = 2;
[Link]("e raised to the power of", power, ":", [Link](power));

Aim: Write a program using string object properties and methods.

Source Code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>String Object Methods Example</title>
<style>
body {
font-family: Arial, sans-serif;
margin: 20px;
}
.output {
margin-top: 10px;
}
</style>
</head>
<body>

<h2>String Object Methods Example</h2>


<div>
<label for="inputString">Enter a String: </label>
<input type="text" id="inputString" placeholder="Enter some text" />
<button onclick="performStringOperations()">Run String Methods</button>
</div>

<div id="result" class="output"></div>

<script>
function performStringOperations() {
// Get the input value from the text box
let inputString = [Link]("inputString").value;

// Check if input is empty


if (inputString === "") {
[Link]("result").innerHTML = "<p>Please enter some text.</p>";
return;
}

// Using string properties and methods


let output = `<h3>String Operations:</h3>`;

// 1. String length
output += `<p><strong>Length of the string:</strong> ${[Link]}</p>`;

// 2. Convert to uppercase
output += `<p><strong>Uppercase:</strong> ${[Link]()}</p>`;

// 3. Convert to lowercase
output += `<p><strong>Lowercase:</strong> ${[Link]()}</p>`;
// 4. Trim whitespace from both ends
output += `<p><strong>Trimmed string:</strong> "${[Link]()}"</p>`;

// 5. Replace characters (first occurrence)


output += `<p><strong>Replace 'a' with 'X':</strong> ${[Link]('a', 'X')}</p>`;

// 6. Extract a substring (first 5 characters)


output += `<p><strong>First 5 characters:</strong> ${[Link](0, 5)}</p>`;

// 7. Find the index of a character ('e')


output += `<p><strong>Index of 'e':</strong> ${[Link]('e')}</p>`;

// 8. Check if the string includes a certain word


let searchWord = "hello";
output += `<p><strong>Does the string include "hello"?:</strong> $
{[Link](searchWord)}</p>`;

// 9. Split the string by spaces


output += `<p><strong>Split by spaces:</strong> ${[Link](" ").join(", ")}</p>`;

// 10. Check if the string starts with 'H'


output += `<p><strong>Starts with 'H'?:</strong> ${[Link]('H')}</p>`;

// 11. Check if the string ends with 't'


output += `<p><strong>Ends with 't'?:</strong> ${[Link]('t')}</p>`;

// Display the results


[Link]("result").innerHTML = output;
}
</script>
</body>
</html>

e. Aim: Write a program using string object properties and methods

Source Code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>String Methods in JavaScript</title>
<style>
body {
font-family: Arial, sans-serif;
padding: 20px;
}
.output {
margin-top: 20px;
}
</style>
</head>
<body>

<h1>String Methods and Properties in JavaScript</h1>

<label for="inputString">Enter a string: </label>


<input type="text" id="inputString" placeholder="Enter some text" />
<button onclick="showStringOperations()">Perform Operations</button>
<div class="output" id="output"></div>

<script>
function showStringOperations() {
// Get the input string from the user
const inputString = [Link]('inputString').value;

// Check if the string is empty


if (!inputString) {
[Link]('output').innerHTML = 'Please enter a string.';
return;
}

// String length (Property)


const stringLength = [Link];

// First and last character (Indexing)


const firstChar = inputString[0];
const lastChar = inputString[[Link] - 1];

// Convert to uppercase and lowercase


const upperString = [Link]();
const lowerString = [Link]();

// Replace a substring
const replacedString = [Link]("World", "JavaScript");

// Find a substring
const indexOfWorld = [Link]("World");
// Trim spaces (if any)
const trimmedString = [Link]();

// Split the string into words


const splitString = [Link](" ");

// Check if the string starts or ends with certain substrings


const startsWithHello = [Link]("Hello");
const endsWithExclamation = [Link]("!");

// Create the result display


const output = `
<h3>String Operations Results:</h3>
<p><strong>Length:</strong> ${stringLength}</p>
<p><strong>First Character:</strong> ${firstChar}</p>
<p><strong>Last Character:</strong> ${lastChar}</p>
<p><strong>Uppercase:</strong> ${upperString}</p>
<p><strong>Lowercase:</strong> ${lowerString}</p>
<p><strong>Replaced String (if "World" exists):</strong> ${replacedString}</p>
<p><strong>Index of "World":</strong> ${indexOfWorld !== -1 ? indexOfWorld :
"Not Found"}</p>
<p><strong>Trimmed String:</strong> '${trimmedString}'</p>
<p><strong>Split String:</strong> ${[Link](", ")}</p>
<p><strong>Starts with "Hello":</strong> ${startsWithHello}</p>
<p><strong>Ends with "!":</strong> ${endsWithExclamation}</p>
`;

// Display the results on the page


[Link]('output').innerHTML = output;
}
</script>

</body>
</html>

f. Aim: Write a program using regex object properties and methods.

Source Code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Regex Methods in JavaScript</title>
<style>
body {
font-family: Arial, sans-serif;
padding: 20px;
}
.output {
margin-top: 20px;
}
</style>
</head>
<body>

<h1>Regex Methods and Properties in JavaScript</h1>

<label for="inputString">Enter a string: </label>


<input type="text" id="inputString" placeholder="Enter some text" />
<br><br>

<label for="regexPattern">Enter a regex pattern: </label>


<input type="text" id="regexPattern" placeholder="e.g., \\d+" />
<button onclick="performRegexOperations()">Perform Regex Operations</button>

<div class="output" id="output"></div>

<script>
function performRegexOperations() {
// Get the input string and regex pattern from the user
const inputString = [Link]('inputString').value;
const regexPattern = [Link]('regexPattern').value;

// Check if both fields are filled


if (!inputString || !regexPattern) {
[Link]('output').innerHTML = 'Please enter both a string and a
regex pattern.';
return;
}

// Create a RegExp object


let regex;
try {
regex = new RegExp(regexPattern);
} catch (e) {
[Link]('output').innerHTML = 'Invalid regex pattern!';
return;
}

// Regex Methods and Properties


// .test() - Tests if the pattern matches the string (returns true/false)
const isMatch = [Link](inputString);

// .exec() - Executes the regex on the string and returns matched groups (if any)
const execResult = [Link](inputString);

// .match() - Returns an array of all matches found in the string


const matchResult = [Link](regex);

// .replace() - Replaces the matched substring with a new substring


const replacedString = [Link](regex,
"<strong>REPLACEMENT</strong>");

// .search() - Returns the index of the first match or -1 if no match is found


const searchResult = [Link](regex);

// .split() - Splits the string into an array based on the regex pattern
const splitResult = [Link](regex);

// Prepare the output display


const output = `
<h3>Regex Operations Results:</h3>
<p><strong>Does the string match the pattern?</strong> ${isMatch}</p>
<p><strong>Matched groups:</strong> ${execResult ? execResult : 'No
match'}</p>
<p><strong>All matches found:</strong> ${matchResult ? [Link](", ") :
'No matches'}</p>
<p><strong>Replaced String:</strong> ${replacedString}</p>
<p><strong>First match position:</strong> ${searchResult !== -1 ? searchResult :
'No match'}</p>
<p><strong>Split result:</strong> ${[Link](", ")}</p>
`;

// Display the results on the page


[Link]('output').innerHTML = output;
}
</script>

</body>
</html>

g. Aim: Write a program using date object properties and methods.

Source Code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Date Object Methods in JavaScript</title>
<style>
body {
font-family: Arial, sans-serif;
padding: 20px;
}
.output {
margin-top: 20px;
}
</style>
</head>
<body>
<h1>JavaScript Date Object Methods and Properties</h1>

<button onclick="showCurrentDate()">Show Current Date and Time</button>


<br><br>

<label for="daysToAdd">Enter number of days to add: </label>


<input type="number" id="daysToAdd" placeholder="Enter number of days" />
<button onclick="addDaysToCurrentDate()">Add Days</button>

<div class="output" id="output"></div>

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

// Get the current date and time properties


const year = [Link]();
const month = [Link]() + 1; // Months are zero-based, so add 1
const day = [Link]();
const hours = [Link]();
const minutes = [Link]();
const seconds = [Link]();
const dayOfWeek = [Link](); // 0-6 (Sunday-Saturday)

// Get the day of the week


const daysOfWeek = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday",
"Friday", "Saturday"];
const dayName = daysOfWeek[dayOfWeek];

// Format and display the current date and time


const formattedDate = `${dayName}, ${month}/${day}/${year} ${hours}:$
{minutes}:${seconds}`;
[Link]('output').innerHTML = `<h3>Current Date and
Time:</h3><p>${formattedDate}</p>`;
}

function addDaysToCurrentDate() {
const daysToAdd = parseInt([Link]('daysToAdd').value);
if (isNaN(daysToAdd)) {
[Link]('output').innerHTML = 'Please enter a valid number of
days.';
return;
}

// Get the current date


const currentDate = new Date();

// Add the specified number of days


[Link]([Link]() + daysToAdd);

// Get the new date


const year = [Link]();
const month = [Link]() + 1; // Months are zero-based
const day = [Link]();

// Format and display the new date


const formattedNewDate = `${month}/${day}/${year}`;
[Link]('output').innerHTML = `<h3>New Date After Adding $
{daysToAdd} Days:</h3><p>${formattedNewDate}</p>`;
}
</script>
</body>
</html>

h. Aim: Write a program to explain user-defined object by using properties, methods,


accessors, constructors and display.

Source Code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>User-Defined Object in JavaScript</title>
<style>
body {
font-family: Arial, sans-serif;
padding: 20px;
}
.output {
margin-top: 20px;
}
</style>
</head>
<body>

<h1>User-Defined Object in JavaScript</h1>

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


<input type="text" id="name" placeholder="Enter your name" />
<br><br>
<label for="age">Enter Age: </label>
<input type="number" id="age" placeholder="Enter your age" />
<br><br>
<button onclick="createPerson()">Create Person Object</button>
<button onclick="displayPerson()">Display Person Info</button>

<div class="output" id="output"></div>

<script>
// Constructor function to create a Person object
function Person(name, age) {
// Properties
[Link] = name;
[Link] = age;

// Method to display the person's info


[Link] = function() {
return `Name: ${[Link]}, Age: ${[Link]}`;
};

// Accessor for 'age' property (getter)


[Link] = function() {
return [Link];
};

// Mutator for 'age' property (setter)


[Link] = function(newAge) {
if (newAge >= 0) {
[Link] = newAge;
} else {
[Link]("Age must be a positive number");
}
};
}

// Function to create a Person object from user input


function createPerson() {
const name = [Link]('name').value;
const age = [Link]('age').value;

if (name && age) {


// Create a new Person object
person = new Person(name, parseInt(age));
[Link]('output').innerHTML = `<p>Person created!</p>`;
} else {
[Link]('output').innerHTML = `<p>Please provide both
name and age.</p>`;
}
}

// Function to display the created Person object


function displayPerson() {
if (person) {
const info = [Link]();
[Link]('output').innerHTML = `<h3>Person
Info:</h3><p>${info}</p>`;
} else {
[Link]('output').innerHTML = `<p>No person object has
been created yet.</p>`;
}
}
</script>

</body>
</html>
Experiment 8
Aim: Java Script Conditional Statements and Loops
a. Write a program which asks the user to enter three integers, obtains the numbers from
the user and outputs HTML text that displays the larger number followed by the words
“LARGER NUMBER” in an information message dialog. If the numbers are equal,
output HTML text as “EQUAL NUMBERS”.
b. Write a program to display week days using switch case.
c. Write a program to print 1 to 10 numbers using for, while and do-while loops.
d. Write a program to print data in object using for-in, for-each and for-of loops
e. Develop a program to determine whether a given number is an ‘ARMSTRONG
NUMBER’ or not. [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]
f. Write a program to display the denomination of the amount deposited in the bank in
terms of 100’s, 50’s, 20’s, 10’s, 5’s, 2’s & 1’s. (Eg: If deposited amount is Rs.163, the
output should be 1 - 100’s, 1-50’s, 1- 10’s, 1-2’s & 1-1’s)

Solution
a. Aim: Write a program which asks the user to enter three integers, obtains the
numbers from the user and outputs HTML text that displays the larger number
followed by the words “LARGER NUMBER” in an information message
dialog. If the numbers are equal, output HTML text as “EQUAL NUMBERS”.

Source Code

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Compare Numbers</title>
<script>
function compareNumbers() {
// Prompt the user to enter three integers
let num1 = parseInt(prompt("Enter the first number:"));
let num2 = parseInt(prompt("Enter the second number:"));
let num3 = parseInt(prompt("Enter the third number:"));

// Check if the numbers are equal


if (num1 === num2 && num2 === num3) {
// Display "EQUAL NUMBERS" if they are all equal
alert("EQUAL NUMBERS");
} else {
// Find the larger number
let largest = [Link](num1, num2, num3);
alert(largest + " LARGER NUMBER");
}
}
</script>
</head>
<body>
<h1>Number Comparison</h1>
<button onclick="compareNumbers()">Compare Numbers</button>
</body>
</html>

b. Aim: Write a program to display week days using switch case.

Source Code

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Weekday Display</title>
<script>
function displayWeekday() {
// Prompt user to enter a number (0-6)
let dayNumber = parseInt(prompt("Enter a number (0-6) to get the
weekday:"));

// Use switch case to determine the weekday


let weekday;
switch(dayNumber) {
case 0:
weekday = "Sunday";
break;
case 1:
weekday = "Monday";
break;
case 2:
weekday = "Tuesday";
break;
case 3:
weekday = "Wednesday";
break;
case 4:
weekday = "Thursday";
break;
case 5:
weekday = "Friday";
break;
case 6:
weekday = "Saturday";
break;
default:
weekday = "Invalid input. Please enter a number between 0 and 6.";
}

// Display the result


alert("The day is: " + weekday);
}
</script>
</head>
<body>
<h1>Weekday Display</h1>
<button onclick="displayWeekday()">Check Weekday</button>
</body>
</html>

c. Aim: Write a program to print 1 to 10 numbers using for, while and do-while
loops.
Source Code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Print Numbers 1 to 10</title>
<script>
function printNumbers() {
// Using for loop
let resultFor = "For Loop: ";
for (let i = 1; i <= 10; i++) {
resultFor += i + " ";
}

// Using while loop


let resultWhile = "While Loop: ";
let i = 1;
while (i <= 10) {
resultWhile += i + " ";
i++;
}

// Using do-while loop


let resultDoWhile = "Do-While Loop: ";
i = 1;
do {
resultDoWhile += i + " ";
i++;
} while (i <= 10);

// Display the results


alert(resultFor + "\n" + resultWhile + "\n" + resultDoWhile);
}
</script>
</head>
<body>
<h1>Print Numbers from 1 to 10</h1>
<button onclick="printNumbers()">Print Numbers</button>
</body>
</html>

d. Aim: Write a program to print data in object using for-in, for-each and for-of
loops.
Source Code

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

<h1>JavaScript Loops to Print Object Data</h1>

<div id="forInLoop"></div>
<div id="forEachLoop"></div>
<div id="forOfLoop"></div>

<script>
// Define an object with some data
const person = {
name: "John",
age: 30,
occupation: "Developer"
};

// 1. Using for-in loop to iterate through object keys


let forInResult = "";
for (let key in person) {
if ([Link](key)) {
forInResult += `${key}: ${person[key]}<br>`;
}
}
[Link]("forInLoop").innerHTML = `<h2>Using for-in
loop:</h2>${forInResult}`;

// 2. Using forEach loop (we need to use [Link] to iterate over the
object in array form)
let forEachResult = "";
[Link](person).forEach(([key, value]) => {
forEachResult += `${key}: ${value}<br>`;
});
[Link]("forEachLoop").innerHTML = `<h2>Using
forEach loop:</h2>${forEachResult}`;

// 3. Using for-of loop (we need to convert the object into an array using
[Link])
let forOfResult = "";
for (const [key, value] of [Link](person)) {
forOfResult += `${key}: ${value}<br>`;
}
[Link]("forOfLoop").innerHTML = `<h2>Using for-of
loop:</h2>${forOfResult}`;

</script>

</body>
</html>

e. Aim: Develop a program to determine whether a given number is an


‘ARMSTRONG NUMBER’ or not. [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]

Source Code

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

<h1>Armstrong Number Checker</h1>


<label for="number">Enter a number:</label>
<input type="number" id="number" placeholder="Enter number">
<button onclick="checkArmstrong()">Check</button>
<p id="result"></p>

<script>
// Function to check if a number is Armstrong
function checkArmstrong() {
const number = parseInt([Link]("number").value);

if (isNaN(number)) {
[Link]("result").innerHTML = "Please enter a valid
number!";
return;
}

const numString = [Link]();


const numDigits = [Link];
let sum = 0;

// Loop through each digit, raise it to the power of the number of digits,
and sum it
for (let i = 0; i < numDigits; i++) {
const digit = parseInt([Link](i));
sum += [Link](digit, numDigits);
}

// Compare the sum to the original number


if (sum === number) {
[Link]("result").innerHTML = `${number} is an
Armstrong number.`;
} else {
[Link]("result").innerHTML = `${number} is not an
Armstrong number.`;
}
}
</script>

</body>
</html>

f. Aim: Write a program to display the denomination of the amount deposited in


the bank in terms of 100’s, 50’s, 20’s, 10’s, 5’s, 2’s & 1’s. (Eg: If deposited
amount is Rs.163, the output should be 1 - 100’s, 1-50’s, 1- 10’s, 1-2’s & 1-
1’s)
Source Code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Bank Denomination Calculator</title>
</head>
<body>

<h1>Denomination of Deposited Amount</h1>


<label for="amount">Enter the deposited amount (in Rs.):</label>
<input type="number" id="amount" placeholder="Enter amount">
<button onclick="calculateDenomination()">Calculate
Denomination</button>

<div id="result"></div>

<script>
function calculateDenomination() {
const amount = parseInt([Link]("amount").value);

if (isNaN(amount) || amount <= 0) {


[Link]("result").innerHTML = "Please enter a valid
amount greater than zero!";
return;
}

let denominations = [100, 50, 20, 10, 5, 2, 1];


let result = '';

// Loop through each denomination and calculate the count


for (let i = 0; i < [Link]; i++) {
let denominationCount = [Link](amount / denominations[i]);

if (denominationCount > 0) {
result += `${denominationCount} - ${denominations[i]}'s<br>`;
}

// Reduce the amount by the value of the denomination counted


amount -= denominationCount * denominations[i];
}

// Display the result


[Link]("result").innerHTML = result;
}
</script>

</body>
</html>
Experiment 9
Aim: Java Script Functions and Events
a. Design a appropriate function should be called to display
i. Factorial of that number ii. Fibonacci series up to that number iii. Prime numbers up to
that number iv. Is it palindrome or not
b. Design a HTML having a text box and four buttons named Factorial, Fibonacci, Prime, and
Palindrome. When a button is pressed an appropriate function should be called to display
i. Factorial of that number ii. Fibonacci series up to that number iii. Prime numbers up to that
number iv. Is it palindrome or not
c. Write a program to validate the following fields in a registration page
i. Name (start with alphabet and followed by alphanumeric and the length should not be less
than 6 characters) ii. Mobile (only numbers and length 10 digits) iii. E-mail (should contain
format like xxxxxxx@[Link])

Solution
a. Aim: Design a appropriate function should be called to display
i. Factorial of that number ii. Fibonacci series up to that number
iii. Prime numbers up to that number iv. Is it palindrome or not
Solution
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Number Operations</title>
</head>
<body>

<h1>Number Operations</h1>

<label for="number">Enter a number:</label>


<input type="number" id="number" placeholder="Enter number">
<button onclick="performOperations()">Submit</button>

<h2>Results:</h2>
<div id="factorialResult"></div>
<div id="fibonacciResult"></div>
<div id="primeResult"></div>
<div id="palindromeResult"></div>

<script>
// Function to calculate factorial of a number
function factorial(n) {
if (n < 0) return "Factorial is not defined for negative numbers";
let fact = 1;
for (let i = 1; i <= n; i++) {
fact *= i;
}
return fact;
}

// Function to generate Fibonacci series up to a given number


function fibonacci(n) {
let fib = [0, 1];
while (fib[[Link] - 1] <= n) {
let nextFib = fib[[Link] - 1] + fib[[Link] - 2];
if (nextFib <= n) [Link](nextFib);
else break;
}
return [Link](", ");
}
// Function to generate prime numbers up to the given number
function primesUpTo(n) {
let primes = [];
for (let i = 2; i <= n; i++) {
let isPrime = true;
for (let j = 2; j <= [Link](i); j++) {
if (i % j === 0) {
isPrime = false;
break;
}
}
if (isPrime) [Link](i);
}
return [Link](", ");
}

// Function to check if a number is palindrome


function isPalindrome(n) {
const str = [Link]();
const reversedStr = [Link]('').reverse().join('');
return str === reversedStr ? "Yes, it is a palindrome." : "No, it is not a palindrome.";
}

// Main function that performs all operations and displays results


function performOperations() {
const number = parseInt([Link]("number").value);

if (isNaN(number) || number <= 0) {


alert("Please enter a valid positive number.");
return;
}

// Factorial
const factResult = factorial(number);
[Link]("factorialResult").innerHTML = `<strong>Factorial:</strong>
${factResult}`;

// Fibonacci series
const fibonacciResult = fibonacci(number);
[Link]("fibonacciResult").innerHTML = `<strong>Fibonacci series
up to ${number}:</strong> ${fibonacciResult}`;

// Prime numbers
const primeResult = primesUpTo(number);
[Link]("primeResult").innerHTML = `<strong>Prime numbers up to
${number}:</strong> ${primeResult}`;

// Palindrome check
const palindromeResult = isPalindrome(number);
[Link]("palindromeResult").innerHTML = `<strong>Palindrome
check:</strong> ${palindromeResult}`;
}
</script>

</body>
</html>

b. Aim: Design a HTML having a text box and four buttons named Factorial, Fibonacci,
Prime, and Palindrome. When a button is pressed an appropriate function should be called to
display
i. Factorial of that number ii. Fibonacci series up to that number iii. Prime numbers up to that
number iv. Is it palindrome or not
Source Code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Number Operations</title>
</head>
<body>

<h1>Number Operations</h1>

<label for="number">Enter a number:</label>


<input type="number" id="number" placeholder="Enter number">
<br><br>

<button onclick="calculateFactorial()">Factorial</button>
<button onclick="calculateFibonacci()">Fibonacci</button>
<button onclick="calculatePrimes()">Prime Numbers</button>
<button onclick="checkPalindrome()">Palindrome Check</button>

<h2>Results:</h2>
<div id="factorialResult"></div>
<div id="fibonacciResult"></div>
<div id="primeResult"></div>
<div id="palindromeResult"></div>

<script>
// Function to calculate factorial of a number
function calculateFactorial() {
const number = parseInt([Link]("number").value);
let result = 1;
if (isNaN(number) || number < 0) {
[Link]("factorialResult").innerHTML = "Please enter a valid
positive number.";
return;
}
for (let i = 1; i <= number; i++) {
result *= i;
}
[Link]("factorialResult").innerHTML = `<strong>Factorial of $
{number}:</strong> ${result}`;
}

// Function to generate Fibonacci series up to a given number


function calculateFibonacci() {
const number = parseInt([Link]("number").value);
if (isNaN(number) || number <= 0) {
[Link]("fibonacciResult").innerHTML = "Please enter a valid
positive number.";
return;
}

let fib = [0, 1];


while (fib[[Link] - 1] <= number) {
let nextFib = fib[[Link] - 1] + fib[[Link] - 2];
if (nextFib <= number) [Link](nextFib);
else break;
}
[Link]("fibonacciResult").innerHTML = `<strong>Fibonacci series
up to ${number}:</strong> ${[Link](", ")}`;
}
// Function to generate prime numbers up to the given number
function calculatePrimes() {
const number = parseInt([Link]("number").value);
if (isNaN(number) || number <= 1) {
[Link]("primeResult").innerHTML = "Please enter a valid number
greater than 1.";
return;
}

let primes = [];


for (let i = 2; i <= number; i++) {
let isPrime = true;
for (let j = 2; j <= [Link](i); j++) {
if (i % j === 0) {
isPrime = false;
break;
}
}
if (isPrime) [Link](i);
}
[Link]("primeResult").innerHTML = `<strong>Prime numbers up to
${number}:</strong> ${[Link](", ")}`;
}

// Function to check if a number is palindrome


function checkPalindrome() {
const number = parseInt([Link]("number").value);
if (isNaN(number)) {
[Link]("palindromeResult").innerHTML = "Please enter a valid
number.";
return;
}

const str = [Link]();


const reversedStr = [Link]('').reverse().join('');
const result = str === reversedStr ? "Yes, it is a palindrome." : "No, it is not a
palindrome.";
[Link]("palindromeResult").innerHTML = `<strong>Palindrome
check:</strong> ${result}`;
}
</script>

</body>
</html>

C. Aim: Write a program to validate the following fields in a registration page


i. Name (start with alphabet and followed by alphanumeric and the length should not be less
than 6 characters) ii. Mobile (only numbers and length 10 digits) iii. E-mail (should contain
format like xxxxxxx@[Link])

Source Code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Registration Form Validation</title>
</head>
<body>

<h1>Registration Form</h1>
<form id="registrationForm" onsubmit="return validateForm()">
<!-- Name Input Field -->
<label for="name">Name (Start with alphabet, followed by alphanumeric, min 6
chars):</label>
<input type="text" id="name" name="name" required><br><br>

<!-- Mobile Input Field -->


<label for="mobile">Mobile (10 digits):</label>
<input type="text" id="mobile" name="mobile" required><br><br>

<!-- Email Input Field -->


<label for="email">Email (xxxxx@[Link]):</label>
<input type="text" id="email" name="email" required><br><br>

<!-- Submit Button -->


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

<div id="errorMessages"></div>

<script>
// Function to validate the form fields
function validateForm() {
// Get values from the form fields
const name = [Link]("name").value;
const mobile = [Link]("mobile").value;
const email = [Link]("email").value;

let errorMessages = [];

// Validate Name (Start with an alphabet, followed by alphanumeric, min length 6)


const nameRegex = /^[A-Za-z][A-Za-z0-9]{5,}$/;
if (![Link](name)) {
[Link]("Name must start with an alphabet, followed by alphanumeric
characters, and be at least 6 characters long.");
}

// Validate Mobile (Only numbers, exactly 10 digits)


const mobileRegex = /^\d{10}$/;
if (![Link](mobile)) {
[Link]("Mobile number must contain exactly 10 digits.");
}

// Validate Email (Format: xxxxxxx@[Link])


const emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
if (![Link](email)) {
[Link]("Email must be in the format: example@[Link].");
}

// If there are error messages, display them and prevent form submission
if ([Link] > 0) {
[Link]("errorMessages").innerHTML = "<ul>" +
[Link](msg => `<li>${msg}</li>`).join('') + "</ul>";
return false; // Prevent form submission
}

return true; // Allow form submission


}
</script>

</body>
</html>

You might also like