CSS Summer 23
CSS Summer 23
CSS Summer 23
(c) Write JavaScript to create a object “student” with properties roll number, name,
branch, year. Delete branch property and display remaining properties of student object.
Ans.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Student Object</title>
</head>
<body>
<h1>Student Object Example</h1>
<div id="output"></div>
<script>
// Create the student object
let student = {
rollNumber: 101,
name: "John Doe",
branch: "Computer Science",
year: "Sophomore"
};
(d) Write a JavaScript that initializes an array called Colors with the names of 3 Colors
and display the array elements.
Ans.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Colors Array Example</title>
</head>
<body>
<h1>Colors Array</h1>
<div id="output"></div>
<script>
// Initialize the Colors array with 3 color names
let Colors = ["Red", "Green", "Blue"];
2. Logical OR (||)
Description: Returns true if at least one of the operands is true; otherwise, it returns false.
Example:
let result = true || false; // result is true
(a) Explain getter and setter properties in JavaScript with suitable example.
Ans.Property getters and setters
1. The accessor properties. They are essentially functions that work on
getting and setting a value.
2. Accessor properties are represented by “getter†and “setter†methods. In
an object literal they are denoted by get and set.
let obj = {
get propName() {
// getter, the code executed on getting obj.propName
},
set propName(value) {
// setter, the code executed on setting obj.propName = value
}
};
3. An object property is a name, a value and a set of attributes. The value
may be replaced by one or two methods, known as setter and a getter.
4. When program queries the value of an accessor property, Javascript
invoke getter method(passing no arguments). The retuen value of this
method become the value of the property access expression.
5. When program sets the value of an accessor property. Javascript invoke
the setter method, passing the value of right-hand side of assignment. This
method is responsible for setting the property value.
ï‚· If property has both getter and a setter method, it is read/write
property.
ï‚· If property has only a getter method , it is read-only property.
ï‚· If property has only a setter method , it is a write-only property.
6. getter works when obj.propName is read, the setter – when it is assigned.
Example:
<html>
<head>
<title>Functions</title>
<body>
<script language="Javascript">
var myCar = {
/* Data properties */
defColor: "blue",
defMake: "Toyota",
(b) Explain Object creation in JavaScript using ‘new’ keyword with adding properties and
methods with example.
Ans.In JavaScript, you can create objects using the new keyword along with a constructor function. This approach allows
you to define properties and methods for the object. Here's a detailed explanation with an example:
Steps for Object Creation Using new
1. Define a Constructor Function: A constructor function is a special type of function that is used to create
objects. It typically starts with an uppercase letter by convention.
2. Add Properties: Inside the constructor function, you can assign properties to the object using the this keyword.
3. Add Methods: You can also define methods inside the constructor function or add them to the prototype for
shared methods among all instances.
4. Create Objects: Use the new keyword to create instances of the object.
Example
Here's a complete example demonstrating object creation using the new keyword:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Object Creation Example</title>
</head>
<body>
<h1>Object Creation Using 'new'</h1>
<div id="output"></div>
<script>
// Step 1: Define the constructor function
function Student(rollNumber, name, branch, year) {
// Step 2: Adding properties
this.rollNumber = rollNumber;
this.name = name;
this.branch = branch;
this.year = year;
}
(c) Write a JavaScript for loop that will iterate from 1 to 15. For each iteration, it
will check if the current number is odd or even and display a message to the screen.
Sample Output : “1 is odd”
“2 is even” ............ .............
Ans.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Odd or Even Checker</title>
</head>
<body>
<h1>Odd or Even Checker</h1>
<div id="output"></div>
<script>
// Get the output div to display the messages
let outputDiv = document.getElementById("output");
// Iterate from 1 to 15
for (let i = 1; i <= 15; i++) {
// Check if the number is odd or even
if (i % 2 === 0) {
outputDiv.innerHTML += `<p>${i} is even</p>`;
} else {
outputDiv.innerHTML += `<p>${i} is odd</p>`;
}
}
</script>
</body>
</html>
(d) Write the use of charCodeAt() and from CharCode() method with syntax and example.
Ans.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>charCodeAt() and fromCharCode() Example</title>
<style>
body {
font-family: Arial, sans-serif;
background-color: #f4f4f4;
color: #333;
margin: 20px;
padding: 20px;
border-radius: 8px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}
h1 {
color: #0056b3;
}
p{
margin: 10px 0;
}
.result {
font-weight: bold;
color: #d9534f; /* Bootstrap danger color */
}
</style>
</head>
<body>
<h1>Using charCodeAt() and fromCharCode()</h1>
<p id="charCodeExample"></p>
<p id="fromCharCodeExample"></p>
<script>
// Example of charCodeAt()
let str = "Hello";
let charCode = str.charCodeAt(0); // Get the Unicode value of 'H'
document.getElementById("charCodeExample").innerHTML =
`The charCodeAt(0) of '${str}' is <span class="result">${charCode}</span>.`;
// Example of fromCharCode()
let char = String.fromCharCode(72); // Create a string from Unicode value 72
document.getElementById("fromCharCodeExample").innerHTML =
`String.fromCharCode(72) returns '<span class="result">${char}</span>'.`;
</script>
</body>
</html>
(c) Explain splice() method of array object with syntax and example.
Ans. The JavaScript array splice() method is used to add/remove the elements to/from the existing array. It returns the
removed elements from an array. The splice() method also modifies the original array.
Syntax:
array.splice(start, deleteCount, item1, item2, ...);
Example:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Array splice() Method Example</title>
</head>
<body>
<h1>JavaScript Array splice() Method</h1>
<div id="output"></div>
<script>
// Original array
let fruits = ["Apple", "Banana", "Mango", "Pineapple", "Grapes"];
<script>
// Function to set a persistent cookie
function setCookie(name, value, days) {
let date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000)); // Convert days to
milliseconds
let expires = "expires=" + date.toUTCString();
document.cookie = `${name}=${value}; ${expires}; path=/`; // Setting the cookie
document.getElementById("output").innerText = `Cookie "${name}" set with value "$
{value}".`;
}
(a) Explain test() and exec() method of Regular Expression object with example.
Ans.
(b) List ways of protecting your web page and describe any one of them.
Ans.Ways of protecting Web Page:
1)Hiding your source code
2)Disabling the right MouseButton
3) Hiding JavaScript
4) Concealing E-mail address.
1) Hiding your source code
The source code for your web page—including your JavaScript—is stored in the
cache, the part of computer memory where the browser stores web pages that
were requested by the visitor. A sophisticated visitor can access the cache and
thereby gain access to the web page source code.
However, you can place obstacles in the way of a potential peeker. First, you can
disable use of the right mouse button on your site so the visitor can't access the
View Source menu option on the context menu. This hides both your HTML code
and your JavaScript from the visitor.
Nevertheless, the visitor can still use the View menu's Source option to display
your source code. In addition, you can store your JavaScript on your web server
instead of building it into your web page. The browser calls the JavaScript from
the web server when it is needed by your web page.
Using this method, the JavaScript isn't visible to the visitor, even if the visitor
views the source code for the web page.
2)Disabling the right MouseButton
The following example shows you how to disable the visitor's right mouse button
while the browser displays your web page. All the action occurs in the JavaScript
that is defined in the <head> tag of the web page.
The JavaScript begins by defining the BreakInDetected() function. This function
is called any time the visitor clicks the right mouse button while the web page is
displayed. It displays a security violation message in a dialog box whenever a
visitor clicks the right mouse button
The BreakInDetected() function is called if the visitor clicks any button other
than the left mouse button.
Example:
<html>
<head>
<title>Lockout Right Mouse Button</title>
<script language=JavaScript>
function BreakInDetected(){
alert('Security Violation')
return false
}
function NetscapeBrowser(e){
if (document.layers||
document.getElementById&&!document.all){
if (e.which==2||e.which==3){
BreakInDetected()
return false
}
}
}
function InternetExploreBrowser(){
if (event.button==2){
BreakInDetected()
return false
}
}
if (document.layers){
document.captureEvents(Event.MOUSEDOWN)
document.onmousedown=NetscapeBrowser()
}
else if (document.all&&!document.getElementById){
document.onmousedown=InternetExploreBrowser()
}
document.oncontextmenu=new Function(
"BreakInDetected();return false")
</script>
</head>
<body>
<table width="100%" border=0>
<tbody>
<tr vAlign=top>
<td width=50>
<a>
<ing height=92 src="rose.jpg"
width=70 border=0
onmouseover="src='rose1.jpg'"
onmouseout="src='rose.jpg'">
</a>
</td>
<td>
<img height=1 src="" width=10>
</td>
<td>
<a>
<cTypeface:Bold><u> Rose Flower</U></b>
</a>
</font><font face="arial, helvetica, sans-serif"
size=-1><BR>Rose Flower
</tr>
</tbody>
</table>
</body>
</html>
3) Hiding JavaScript
You can hide your JavaScript from a visitor by storing it in an external fi le on
your web server. The external fi le should have the .js fi le extension. The browser
then calls the external file whenever the browser encounters a JavaScript element
in the web page. If you look at the source code for the web page, you'll see
reference to the external .js fi le, but you won't see the source code for the
JavaScript.
The next example shows how to create and use an external JavaScript file. First
you must tell the browser that the content of the JavaScript is located in an
external
file on the web server rather than built into the web page. You do this by assigning
the fi le name that contains the JavaScripts to the src attribute of the <script>
tag, as shown here:
<script src="MyJavaScripts.js"
language="Javascript" type="text/javascript">
Next, you need to defi ne empty functions for each function that you define in the
external JavaScript fi le.
<html >
<head>
<title>Using External JavaScript File</title>
<script src="myJavaScript.js" language="Javascript" type="text/javascript">
function OpenNewWindow(book) {
}
</script>
</head>
<body>
<tablewidth="100%" border=0>
<tbody>
<tr vAlign=top>
<td width=50>
<a>
<img height=92 src="rose.jpg" width=70 border=0 name='cover'>
</a>
</td>
<td>
<img height=1 src="" width=10>
</td>
<td>
<a onmouseover="OpenNewWindow(1)" onmouseout="MyWindow.close()">
<b><u>Rose </u></b>
</a>
<br>
<a onmouseover="OpenNewWindow(2)" onmouseout="MyWindow.close()">
<b><u>Sunflower</U></b>
</a>
<br>
<A onmouseover="OpenNewWindow(3)" onmouseout="MyWindow.close()">
<b><u>Jasmine </u></b>
</a>
</td>
</tr>
</tbody>
</table>
</body>
</html>
The final step is to create the external JavaScript fi le. You do this by placing all
function definitions into a new fi le and then saving the fi le using the .js
extension.
MyJavaScript.js file:
function OpenNewWindow(book) {
if (book== 1)
{
document.cover.src='rose.jpg'
MyWindow = window.open('', 'myAdWin', 'titlebar=0 status=0, toolbar=0,
location=0, menubar=0, directories=0, resizable=0, height=50,
width=150,left=500,top=400')
MyWindow.document.write( 'Rose flower')
}
if (book== 2)
{
document.cover.src='sunflower.jpeg'
MyWindow = window.open('', 'myAdWin', 'titlebar=0 status=0, toolbar=0,
location=0, menubar=0, directories=0, resizable=0, height=50,
width=150,left=500,top=500')
MyWindow.document.write( 'sunflower flower')
}
if (book== 3)
{
document.cover.src='jasmine.gif'
MyWindow = window.open('', 'myAdWin', 'titlebar=0
status=0, toolbar=0, location=0, menubar=0, directories=0, resizable=0,
height=50,
width=150,left=500,top=600')
MyWindow.document.write( 'Jasmine Flower')
}
}
After you create the external JavaScript fi le, defi ne empty functions for each
function that is contained in the external JavaScript fi le, and reference the
external
JavaScript fi le in the src attribute of the <script> tag, you're all set.
4) Concealing E-mail address:
Many of us have endured spam at some point and have probably blamed every
merchant we ever patronized for selling our e-mail address to spammers. While
e-mail addresses are commodities, it's likely that we ourselves are the culprits
who invited spammers to steal our e-mail addresses.
Here's what happens: Some spammers create programs called bots that surf the
Net looking for e-mail addresses that are embedded into web pages, such as those
placed there by developers to enable visitors to contact them. The bots then strip
these e-mail addresses from the web page and store them for use in a spam attack.
This technique places developers between a rock and a hard place. If they place
their e-mail addresses on the web page, they might get slammed by spammers. If
they don't display their e-mail addresses, visitors will not be able to get in touch
with the developers.
The solution to this common problem is to conceal your e-mail address in the
source code of your web page so that bots can't fi nd it but so that it still appears
on the web page. Typically, bots identify e-mail addresses in two ways: by the
mailto: attribute that tells the browser the e-mail address to use when the visitor
wants to respond to the web page, and by the @ sign that is required of all e-mail
addresses. Your job is to confuse the bots by using a JavaScript to generate the
e-mail address dynamically. However, you'll still need to conceal the e-mail
address in your JavaScript, unless the JavaScript is contained in an external
JavaScript file, because a bot can easily recognize the mailto: attribute and the @
sign in a JavaScript.
Bots can also easily recognize when an external fi le is referenced. To conceal an
e-mail address, you need to create strings that contain part of the e-mail address
and then build a JavaScript that assembles those strings into the e-mail address,
which is then written to the web page.
The following example illustrates one of many ways to conceal an e-mail address.
It also shows you how to write the subject line of the e-mail. We begin by
creating four strings:
• The first string contains the addressee and the domain along with symbols &, *,
and _ (underscore) to confuse the bot.
• The second and third strings contain portions of the mailto: attribute name.
Remember that the bot is likely looking for mailto:.
• The fourth string contains the subject line. As you'll recall from your HTML
training, you can generate the TO, CC, BCC, subject, and body of an e-mail from
within a web page.
You then use these four strings to build the e-mail address. This process starts by
using the replace() method of the string object to replace the & with the @ sign
and the * with a period (.). The underscores are replaced with nothing, which is
the
same as simply removing the underscores from the string.
All the strings are then concatenated and assigned to the variable b, which is then
assigned the location attribute of the window object. This calls the e-mail program
on the visitor's computer and populates the TO and Subject lines with the strings
generated by the JavaScript.
<html>
<head>
<title>Conceal Email Address</title>
<script>
function CreateEmailAddress(){
var x = manish*c_o_m'
var y = 'mai'
var z = 'lto'
var s = '?subject=Customer Inquiry'
x = x.replace('&','@')
x = x.replace('*','.')
x = x.replace('_','')
x = x.replace('_','')
var b = y + z +':'+ x + s
window.location=b
}
-->
</script>
</head>
<body>
<input type="button" value="Help"
onclick="CreateEmailAddress()">
</body>
</html>
(c) Explain how to create and display Rotating Banner in JavaScript with example.
Ans.To create a rotating banner in JavaScript, we can use an array to store image URLs or text, and set a timer to update
the banner content at specific intervals. This example will demonstrate creating an image-based rotating banner with
JavaScript, CSS, and HTML.
Steps to Create a Rotating Banner
1. HTML Structure: Create an HTML element to serve as the banner display area.
2. CSS Styling: Style the banner container to set the size and make the transitions smooth.
3. JavaScript Logic: Use JavaScript to rotate through banner items (images or text) periodically.
Example Code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Rotating Banner Example</title>
<style>
/* Banner container styling */
#banner {
width: 300px;
height: 200px;
border: 2px solid #333;
overflow: hidden;
position: relative;
text-align: center;
}
/* Image styling */
#banner img {
width: 100%;
height: 100%;
object-fit: cover;
transition: opacity 0.5s ease-in-out;
}
</style>
</head>
<body>
<h2>Rotating Banner</h2>
<div id="banner">
<img src="https://via.placeholder.com/300x200?text=Image+1" alt="Banner Image 1">
</div>
<script>
// Array of image URLs
const images = [
"https://via.placeholder.com/300x200?text=Image+1",
"https://via.placeholder.com/300x200?text=Image+2",
"https://via.placeholder.com/300x200?text=Image+3"
];
// Change the source of the image to the next one in the array
img.style.opacity = 0; // Fade out transition
setTimeout(() => {
img.src = images[currentIndex];
img.style.opacity = 1; // Fade in transition
}, 500); // Duration of fade-out effect
}
</body>
</html>
(d) Explain text and image rollover with suitable example.
Ans.Rollover means a webpage changes when the user moves his or her mouse over an object
on the page. It is often used in advertising. There are two ways to create rollover, using
plain HTML or using a mixture of JavaScript and HTML. We will demonstrate the creation
of rollovers using both methods.
The keyword that is used to create rollover is the <onmousover> event.
For example, we want to create a rollover text that appears in a text area. The text “What
is rollover?†appears when the user place his or her mouse over the text area and the
rollover text changes to “Rollover means a webpage changes when the user moves his or
her mouse over an object on the page†when the user moves his or her mouse away from
the text area.
The HTML script is shown in the following example:
Example:
<html>
<head></head>
<Body>
<textarea rows="2" cols="50" name="rollovertext" onmouseover="this.value='What
is rollover?'"
onmouseout="this.value='Rollover means a webpage changes when the user moves
his or her mouse over an object on the page'"></textarea>
</body>
</html>
(e) What is Status bar and how to display moving message on the status line of a window
using JavaScript ?
Ans.The status bar is a small area at the bottom of a browser window or application window that typically provides
information about the current state, actions, or context of the window. In the past, the status bar was frequently used in
web browsers and applications to display various types of messages, such as link destinations when hovering over a link,
loading progress, or error messages.
Characteristics of the Status Bar
1. Location:
a. Usually located at the bottom of the browser or application window.
2. Information Displayed:
a. Page Loading Status: Shows loading progress or messages like "Loading..." when a page is still
rendering.
b. Link Information: Displays the URL when a user hovers over a hyperlink, indicating where the link
will lead.
c. Error Messages or Warnings: Shows network-related issues, errors, or warnings.
d. Additional Information: In desktop applications, it can display things like coordinates (in graphic
software), word count (in word processors), or other useful data depending on the application.
3. JavaScript Control:
a. JavaScript can set the window.status property to display custom messages in the status bar, but modern
browsers have restricted this feature due to security and UX reasons.
4. Modern Usage:
a. Most modern browsers (such as Chrome, Firefox, and Edge) no longer have a visible status bar by
default.
b. Status-related information has largely moved to temporary overlays or tooltips near the bottom of the
screen, or to the address bar.
Example of Status Bar in Browsers
In older browsers or custom applications, you might see:
A message like "Loading page..." while a new page loads.
A URL preview when hovering over a link.
Custom messages set by JavaScript (if supported), such as "Welcome to our site!".
In modern web to display a moving (scrolling) message on the status line (the status bar) of a window using JavaScript,
you can create a loop that updates the window.status property repeatedly to create a scrolling effect. The window.status is
an old technique, as modern browsers may not fully support setting messages in the status bar due to security and UX
reasons. However, if you want to experiment with it, here is how you can do it.
Example
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Scrolling Status Line Message</title>
</head>
<body>
<script>
// Message to display
let message = " Welcome to our website! "; // Initial message
let position = 0; // Starting position of the scrolling message
</body>
</html>
(a) Write HTML code to design a form that displays two textboxes for accepting two
numbers, one textbox for accepting result and two buttons as ADDITION and
SUBTRACTION. Write proper JavaScript such that when the user clicks on any one of the
button, respective operation will be performed on two numbers and result will be displayed
in result textbox.
Ans.
<!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;
margin: 50px;
}
.calculator {
max-width: 300px;
margin: auto;
padding: 20px;
border: 1px solid #ccc;
border-radius: 5px;
box-shadow: 0 2px 10px rgba(0,0,0,0.1);
}
input[type="number"] {
width: 100%;
padding: 10px;
margin: 10px 0;
border: 1px solid #ccc;
border-radius: 4px;
}
button {
width: 48%;
padding: 10px;
border: none;
border-radius: 4px;
cursor: pointer;
margin: 5px 1%;
font-size: 16px;
}
button:hover {
opacity: 0.9;
}
.add {
background-color: #28a745;
color: white;
}
.subtract {
background-color: #dc3545;
color: white;
}
#result {
background-color: #f8f9fa;
color: #333;
}
</style>
</head>
<body>
<div class="calculator">
<h2>Simple Calculator</h2>
<input type="number" id="number1" placeholder="Enter first number" required>
<input type="number" id="number2" placeholder="Enter second number" required>
<input type="text" id="result" placeholder="Result" disabled>
<div>
<button class="add" onclick="addNumbers()">ADDITION</button>
<button class="subtract" onclick="subtractNumbers()">SUBTRACTION</button>
</div>
</div>
<script>
function addNumbers() {
// Get the values from the input fields
const num1 = parseFloat(document.getElementById("number1").value);
const num2 = parseFloat(document.getElementById("number2").value);
// Perform addition
const sum = num1 + num2;
// Display the result
document.getElementById("result").value = sum;
}
function subtractNumbers() {
// Get the values from the input fields
const num1 = parseFloat(document.getElementById("number1").value);
const num2 = parseFloat(document.getElementById("number2").value);
// Perform subtraction
const difference = num1 - num2;
// Display the result
document.getElementById("result").value = difference;
}
</script>
</body>
</html>
(b) Write HTML code to design a form that displays two buttons START and STOP. Write
a JavaScript code such that when user clicks on START button, real time digital clock will
be displayed on screen. When user clicks on STOP button, clock will stop displaying time.
(Use Timer methods)
Ans.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Digital Clock</title>
<style>
body {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
height: 100vh;
font-family: Arial, sans-serif;
}
#clock {
font-size: 2em;
margin: 20px;
}
button {
padding: 10px 20px;
font-size: 1em;
margin: 5px;
cursor: pointer;
}
</style>
</head>
<body>
<div id="clock">00:00:00</div>
<button id="startBtn">START</button>
<button id="stopBtn">STOP</button>
<script>
let timer; // To store the timer reference
const clockElement = document.getElementById('clock');
function startClock() {
// Start the timer
timer = setInterval(() => {
const now = new Date();
const hours = String(now.getHours()).padStart(2, '0');
const minutes = String(now.getMinutes()).padStart(2, '0');
const seconds = String(now.getSeconds()).padStart(2, '0');
clockElement.textContent = `${hours}:${minutes}:${seconds}`;
}, 1000);
}
function stopClock() {
// Stop the timer
clearInterval(timer);
}
document.getElementById('startBtn').addEventListener('click', startClock);
document.getElementById('stopBtn').addEventListener('click', stopClock);
</script>
</body>
</html>
(c) Write HTML code to design a form that displays textboxes for accepting UserID and
Aadhar No. and a SUBMIT button. UserID should contain 10 alphanumeric characters
and must start with Capital Letter. Aadhar No. should contain 12 digits in the format nnnn
nnnn nnnn. Write JavaScript code to validate the UserID and Aadhar No. when the user
clicks on SUBMIT button.
Ans.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>UserID and Aadhar Validation</title>
<style>
body {
font-family: Arial, sans-serif;
margin: 50px;
}
.form-container {
max-width: 400px;
margin: auto;
padding: 20px;
border: 1px solid #ccc;
border-radius: 5px;
box-shadow: 0 2px 10px rgba(0,0,0,0.1);
}
input[type="text"] {
width: 100%;
padding: 10px;
margin: 10px 0;
border: 1px solid #ccc;
border-radius: 4px;
}
button {
width: 100%;
padding: 10px;
border: none;
border-radius: 4px;
cursor: pointer;
background-color: #007bff;
color: white;
font-size: 16px;
}
button:hover {
background-color: #0056b3;
}
.error {
color: red;
font-size: 14px;
margin-top: 10px;
}
</style>
</head>
<body>
<div class="form-container">
<h2>UserID and Aadhar Validation</h2>
<input type="text" id="userID" placeholder="Enter UserID (10 alphanumeric, start with
capital)" required>
<input type="text" id="aadharNo" placeholder="Enter Aadhar No. (12 digits, format: nnnn
nnnn nnnn)" required>
<button onclick="validateForm()">SUBMIT</button>
<div id="error-message" class="error"></div>
</div>
<script>
function validateForm() {
// Clear any previous error messages
document.getElementById("error-message").innerText = "";
// Regular expression for UserID: must start with a capital letter and be 10 characters long
const userIDPattern = /^[A-Z][a-zA-Z0-9]{9}$/;
// Regular expression for Aadhar No: must be 12 digits and formatted as nnnn nnnn nnnn
const aadharPattern = /^\d{4} \d{4} \d{4}$/;
// Validate UserID
if (!userIDPattern.test(userID)) {
errorMessage += "Invalid UserID: Must start with a capital letter and be exactly 10
alphanumeric characters.\n";
}
</body>
</html>
Ans. In JavaScript, you can evaluate the selected value of a group of radio buttons by checking
which button is checked. Each radio button within a group has the same name attribute, which
allows the browser to treat them as a single selectable group.
Example:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Radio Button Evaluation Example</title>
</head>
<body>
<h2>Choose your favorite genre:</h2>
<form id="genreForm">
<label><input type="radio" name="genre" value="Rock"> Rock</label><br>
<label><input type="radio" name="genre" value="Pop"> Pop</label><br>
<label><input type="radio" name="genre" value="Jazz"> Jazz</label><br>
<label><input type="radio" name="genre" value="Classical"> Classical</label><br>
<button type="button" onclick="evaluateRadioButton()">Submit</button>
</form>
<p id="result"></p>
<script>
function evaluateRadioButton() {
// Get all radio buttons with the name 'genre'
const radioButtons = document.getElementsByName('genre');
let selectedValue = null;
// Loop through the radio buttons to find the selected one
for (const radioButton of radioButtons) {
if (radioButton.checked) {
selectedValue = radioButton.value;
break;
}
}
// Display the selected value or a message if none are selected
const resultElement = document.getElementById('result');
if (selectedValue) {
resultElement.textContent = `You selected: ${selectedValue}`;
} else {
resultElement.textContent = 'Please select a genre.';
}
}
</script>
</body>
</html>
</body>
</html>