0% found this document useful (0 votes)
14 views24 pages

A. Write A Program To Embed Internal and External Javascript in A Web Page

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

A. Write A Program To Embed Internal and External Javascript in A Web Page

Java script programs
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 24

6.

Applying JavaScript - internal and external, I/O, Type Conversion

a. Write a program to embed internal and external JavaScript in a web page.

HTML Code

<html>
<head>
<title>Internal and External JavaScript</title>
<script>
function showInternalMessage()
{
alert('This is Internal JavaScript');
}
</script>
<script src="a.js"></script>
</head>
<body>
<button onclick="showInternalMessage()">Internal JS</button>
<button onclick="showExternalMessage()">External JS</button>
</body>
</html>

JS Code
function showExternalMessage()
{
alert('This is External JavaScript');
}

b. Write a program to explain the different ways for displaying output.

<html>
<head>
<title>Output Methods</title>
<script>
function displayOutput()
{
alert('This is an alert message');
console.log('This is a console log');
document.write('<p>This is document.write output</p>');
document.getElementById('outputDiv').innerHTML = 'This is inner HTML output';
}
</script>
</head>
<body onload="displayOutput()">
<div id="outputDiv" style="margin-top: 20px;"></div>
</body>
</html>
c. Write a program to explain the different ways for taking input.

<html>
<head>
<title>Input Methods</title>
<script>
function takeInput()
{
const promptInput = prompt('Enter your name:');
alert('You entered: ' + promptInput);
const formInput = document.getElementById('nameInput').value;
alert('Form input: ' + formInput);
}
</script>
</head>
<body>
<form onsubmit="event.preventDefault(); takeInput();">
<label for="nameInput">Enter your name:</label>
<input type="text" id="nameInput">
<button type="submit">Submit</button>
</form>
</body>
</html>

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

<html>
<head>
<title>Voter Eligibility</title>
<script>
function checkVoterEligibility()
{
const name = prompt('Enter your name:');
const age = parseInt(prompt('Enter your age:'));
const canVote = age >= 18 ? 'Yes' : 'No';
const tableRow = `
<tr>
<td>${name}</td>
<td>${age}</td>
<td>${canVote}</td>
</tr>
`;
document.getElementById('voterTable').innerHTML += tableRow;
}
</script>
</head>
<body>
<button onclick="checkVoterEligibility()">Check Voter Eligibility</button>
<table border="1" style="margin-top: 20px;">
<thead>
<tr>
<th>Name</th>
<th>Age</th>
<th>Can Vote</th>
</tr>
</thead>
<tbody id="voterTable"></tbody>
</table>
</body>
</html>
7. Java Script Pre-defined and User-defined Objects

a. Write a program using document object properties and methods.

<html>
<head>
<title>Document Object Example</title>
</head>
<body>
<h1 id="header">Hello, World!</h1>
<p id="para">This is a sample paragraph.</p>
<button onclick="changeContent()">Click Me</button>
<script>
function changeContent()
{
document.getElementById('header').innerText = 'Content Changed!';
document.body.style.backgroundColor = 'lightblue';
const newPara = document.createElement('p');
newPara.innerText = 'This is a dynamically added paragraph.';
document.body.appendChild(newPara);
}
</script>
</body>
</html>

b. Write a program using window object properties and methods.

<html>
<head>
<title>Window Object Example</title>
</head>
<body>
<button onclick="showAlert()">Show Alert</button>
<button onclick="openNewWindow()">Open New Window</button>
<script>
function showAlert()
{
window.alert('This is an alert from the window object!');
}
function openNewWindow()
{
window.open('https://www.google.com', '_blank');
}
</script>
</body>
</html>

c. Write a program using array object properties and methods.


<html>
<head>
<title>Array Object Example</title>
</head>
<body>
<div id="output"></div>
<script>
const numbers = [1, 2, 3, 4, 5];
let output = '';
output += 'Original Array: ' + numbers + '<br>';
output += 'Array length: ' + numbers.length + '<br>';
numbers.push(6);
output += 'After push: ' + numbers + '<br>';
numbers.pop();
output += 'After pop: ' + numbers + '<br>';
output += 'Contains 3? ' + numbers.includes(3) + '<br>';
output += 'Array elements: <br>';
numbers.forEach(num => output += num + '<br>');
document.getElementById('output').innerHTML = output;
</script>
</body>
</html>

d. Write a program using math object properties and methods.

<html>
<head>
<title>Math Object Example</title>
</head>
<body>
<div id="output"></div>
<script>
let output = '';
output += 'Random Number: ' + Math.random() + '<br>';
output += 'Rounded Number (4.7): ' + Math.round(4.7) + '<br>';
output += 'Square Root of 25: ' + Math.sqrt(25) + '<br>';
output += 'Power of 2^3: ' + Math.pow(2, 3) + '<br>';
output += 'Absolute Value of -10: ' + Math.abs(-10) + '<br>';
document.getElementById('output').innerHTML = output;
</script>
</body>
</html>

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

<html>
<head>
<title>String Object Example</title>
</head>
<body>
<div id="output"></div>
<script>
const text = 'Hello, JavaScript!';
let output = '';
output += 'Original String: ' + text + '<br>';
output += 'Length of String: ' + text.length + '<br>';
output += 'Uppercase: ' + text.toUpperCase() + '<br>';
output += 'Substring (5-10): ' + text.substring(5, 10) + '<br>';
output += 'Replaced String: ' + text.replace('JavaScript', 'World') + '<br>';
output += 'Character at index 7: ' + text.charAt(7) + '<br>';
document.getElementById('output').innerHTML = output;
</script>
</body>
</html>

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

<html>
<head>
<title>Regex Object Example</title>
</head>
<body>
<div id="output"></div>
<script>
const text = "My email is [email protected] and I use it daily.";
const emailRegex = /\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b/;
const emailMatch = text.match(emailRegex);
let output = '';
if (emailMatch)
{
output += "Extracted Email: " + emailMatch[0] + "<br>";
}
else
{
output += "No email found in the text.<br>";
}
const redactedText = text.replace(emailRegex, '[REDACTED]');
output += "Redacted Text: " + redactedText;
document.getElementById('output').innerHTML = output;
</script>
</body>
</html>

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

<html>
<head>
<title>Date Object Example</title>
</head>
<body>
<div id="output"></div>
<script>
const currentDate = new Date();
let output = '';
output += 'Current Date and Time: ' + currentDate + '<br>';
output += 'Year: ' + currentDate.getFullYear() + '<br>';
output += 'Month: ' + (currentDate.getMonth() + 1) + '<br>';
output += 'Day of the Month: ' + currentDate.getDate() + '<br>';
output += 'Day of the Week: ' + currentDate.getDay() + '<br>';
output += 'Hours: ' + currentDate.getHours() + '<br>';
output += 'Minutes: ' + currentDate.getMinutes() + '<br>';
output += 'Seconds: ' + currentDate.getSeconds() + '<br>';
output += 'Formatted Date: ' + currentDate.toDateString() + '<br>';
output += 'Formatted Time: ' + currentDate.toTimeString() + '<br>';
document.getElementById('output').innerHTML = output;
</script>
</body>
</html>

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


accessors, constructors and display

<html>
<head>
<title>User-Defined Object Example</title>
</head>
<body>
<div id="output"></div>
<script>
function Person(firstName, lastName, age)
{
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
this.getFullName = function()
{
return this.firstName + ' ' + this.lastName;
};
this.getAge = function()
{
return this.age;
};
this.setAge = function(newAge)
{
if (newAge > 0)
{
this.age = newAge;
} else {
console.log("Invalid age.");
}
};
}
const person1 = new Person('John', 'Doe', 25);
let output = '';
output += 'Full Name: ' + person1.getFullName() + '<br>';
output += 'Age: ' + person1.getAge() + '<br>';
person1.setAge(30);
output += 'Updated Age: ' + person1.getAge() + '<br>';
document.getElementById('output').innerHTML = output;
</script>
</body>
</html>
8. Java Script Conditional Statements and loops

a. Write a program which ask the user to enter three integers obtains the numbers from
the user and outputs HTML text that display the large numbered followed by the words
'LARGER NUMBER' in an information message dialog if the numbers are equal output
HTML text as 'EQUAL NUMBERS'.

<html>
<head>
<title>Find Larger Number</title>
<style>
body
{
font-family: 'Times New Roman';
text-align: center;
margin-top: 50px;
}
.message
{
font-size: 20px;
color: blue;
}
.large-number
{
color: green;
}
</style>
</head>
<body>
<h1>Find the Largest Number</h1>
<p>Enter three integers:</p>
<input type="number" id="num1" placeholder="First Number">
<input type="number" id="num2" placeholder="Second Number">
<input type="number" id="num3" placeholder="Third Number">
<br>
<br>
<button onclick="findLargest()">Submit</button>
<p class="message" id="result"></p>
<script>
function findLargest()
{
const num1 = parseInt(document.getElementById('num1').value);
const num2 = parseInt(document.getElementById('num2').value);
const num3 = parseInt(document.getElementById('num3').value);
let resultMessage = "";
if (num1 === num2 && num2 === num3)
{
resultMessage = "EQUAL NUMBERS";
document.getElementById('result').style.color = "blue";
}
else
{
const largest = Math.max(num1, num2, num3);
resultMessage = `LARGER NUMBER: ${largest}`;
document.getElementById('result').style.color = "green";
}
document.getElementById('result').innerText = resultMessage;
}
</script>
</body>
</html>

b. Write a program to display weekdays using switch case

<html>
<head>
<title>Weekday Display</title>
<style>
body
{
font-family: 'Times New Roman';
text-align: center;
margin-top: 50px;
}
.message
{
font-size: 20px;
color: blue;
}
</style>
</head>
<body>
<h1>Weekday Finder</h1>
<p>Enter a number (1-7)</p>
<input type="number" id="dayNumber" placeholder="Enter a number" min="1" max="7">
<br><br>
<button onclick="displayWeekday()">Find Weekday</button>
<p class="message" id="result"></p>
<script>
function displayWeekday()
{
const dayNumber = parseInt(document.getElementById('dayNumber').value);
let weekday = "";
switch (dayNumber)
{
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;
case 7:
weekday = "Sunday";
break;
default:
weekday = "Invalid input! Please enter a number between 1 and 7";
}
document.getElementById('result').innerText = weekday;
}
</script>
</body>
</html>

c. Write a program to print 1 to 10 numbers using for , while and do-while loops.

Using For Loop

<html>
<head>
<title>Print Numbers Using For Loop</title>
<style>
body
{
font-family: 'Times New Roman';
text-align: center;
margin-top: 50px;
}
.output
{
font-size: 18px;
color: green;
}
</style>
</head>
<body>
<h1>Print Numbers Using For Loop</h1>
<button onclick="printUsingFor()">Print Numbers</button>
<p class="output" id="result"></p>
<script>
function printUsingFor()
{
let result = "Numbers: ";
for (let i = 1; i <= 10; i++)
{
result += i + " ";
}
document.getElementById('result').innerText = result.trim();
}
</script>
</body>
</html>
Using While Loop

<html>
<head>
<title>Print Numbers Using While Loop</title>
<style>
body
{
font-family: 'Times New Roman';
text-align: center;
margin-top: 50px;
}
.output
{
font-size: 18px;
color: green;
}
</style>
</head>
<body>
<h1>Print Numbers Using While Loop</h1>
<button onclick="printUsingWhile()">Print Numbers</button>
<p class="output" id="result"></p>
<script>
function printUsingWhile()
{
let result = "Numbers: ";
let i = 1;
while (i <= 10)
{
result += i + " ";
i++;
}
document.getElementById('result').innerText = result.trim();
}
</script>
</body>
</html>

Using do-while Loop

<html>
<head>
<title>Print Numbers Using Do-While Loop</title>
<style>
body
{
font-family: 'Times New Roman';
text-align: center;
margin-top: 50px;
}
.output
{
font-size: 18px;
color: green;
}
</style>
</head>
<body>
<h1>Print Numbers Using Do-While Loop</h1>
<button onclick="printUsingDoWhile()">Print Numbers</button>
<p class="output" id="result"></p>
<script>
function printUsingDoWhile()
{
let result = "Numbers: ";
let i = 1;
do
{
result += i + " ";
i++;
}
while (i <= 10);
document.getElementById('result').innerText = result.trim();
}
</script>
</body>
</html>

d. Develop a program to print data in object using for-in and for-of loops

Using For-In Loop

<html>
<head>
<title>For-In Loop Example</title>
<style>
body
{
font-family: 'Times New Roman';
text-align: center;
margin-top: 50px;
}
.output
{
font-size: 18px;
color: blue;
}
</style>
</head>
<body>
<h1>Print Object Data Using For-In</h1>
<button onclick="printUsingForIn()">Print Data</button>
<p class="output" id="result"></p>
<script>
function printUsingForIn()
{
const data =
{
name: "Alice",
age: 25,
profession: "Engineer",
country: "USA"
};
let result = "Data: ";
for (const key in data)
{
result += `${key}: ${data[key]} | `;
}
document.getElementById('result').innerText = result.trim();
}
</script>
</body>
</html>

Using For-Of Loops

<html>
<head>
<title>For-Of Loop Example</title>
<style>
body
{
font-family: 'Times New Roman';
text-align: center;
margin-top: 50px;
}
.output
{
font-size: 18px;
color: green;
}
</style>
</head>
<body>
<h1>Print Object Values Using For-Of</h1>
<button onclick="printUsingForOf()">Print Data</button>
<p class="output" id="result"></p>
<script>
function printUsingForOf()
{
const data =
{
name: "Alice",
age: 25,
profession: "Engineer",
country: "USA"
};
let result = "Values: ";
for (const value of Object.values(data))
{
result += `${value} | `;
}
document.getElementById('result').innerText = result.trim();
}
</script>
</body>
</html>
e. Develop a program to determine whether a given number is ‘ 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 1^3+5^3+3^3 = 153]

<html>
<head>
<title>Armstrong Number Checker</title>
<style>
body
{
font-family: 'Times New Roman';
text-align: center;
margin-top: 50px;
}
.output
{
font-size: 18px;
color: green;
}
.error
{
font-size: 18px;
color: red;
}
</style>
</head>
<body>
<h1>Armstrong Number Checker</h1>
<p>Enter a number to check if it is an Armstrong Number</p>
<input type="number" id="numberInput" placeholder="Enter a number">
<br><br>
<button onclick="checkArmstrong()">Check</button>
<p id="result" class="output"></p>
<script>
function checkArmstrong()
{
const num = document.getElementById('numberInput').value;
if (!num || num < 0) {
document.getElementById('result').innerText = "Please enter a positive number!";
document.getElementById('result').className = "error";
return;
}
const digits = num.split("").map(Number);
const numOfDigits = digits.length;
const sum = digits.reduce((acc, digit) => acc + Math.pow(digit, numOfDigits), 0);
if (parseInt(num) === sum)
{
document.getElementById('result').innerText = `${num} is an Armstrong Number!`;
document.getElementById('result').className = "output";
}
else
{
document.getElementById('result').innerText = `${num} is NOT an Armstrong Number.`;
document.getElementById('result').className = "error";
}
}
</script>
</body>
</html>

f. Write a program to display the denomination of 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 in Rs:163 , the output
should be 1-100’s , 1-50’s , 1-2’s & 1-1’s)

<html>
<head>
<title>Bank Denomination Calculator</title>
<style>
body
{
font-family: 'Times New Roman';
text-align: center;
margin-top: 50px;
}
.output
{
font-size: 18px;
color: green;
}
.error
{
font-size: 18px;
color: red;
}
</style>
</head>
<body>
<h1>Bank Denomination Calculator</h1>
<p>Enter the amount you want to deposit</p>
<input type="number" id="amountInput" placeholder="Enter amount in Rs" min="1">
<br><br>
<button onclick="calculateDenominations()">Calculate Denominations</button>
<p id="result" class="output"></p>
<script>
function calculateDenominations()
{
const amount = parseInt(document.getElementById('amountInput').value);
if (isNaN(amount) || amount <= 0) {
document.getElementById('result').innerText = "Please enter a valid positive amount!";
document.getElementById('result').className = "error";
return;
}
const denominations = [100, 50, 20, 10, 5, 2, 1];
let remainingAmount = amount;
let result = `Denominations for Rs.${amount}: `;
for (const denom of denominations) {
const count = Math.floor(remainingAmount / denom);
if (count > 0) {
result += `${count} - ₹${denom}'s, `;
remainingAmount %= denom;
}
}
document.getElementById('result').innerText = result.slice(0, -2); // Remove trailing comma
and space
document.getElementById('result').className = "output";
}
</script>
</body>
</html>

9. 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

i. Factorial of that number

<html>
<head>
<title>Factorial Calculator</title>
<style>
body
{
font-family: 'Times New Roman';
text-align: center;
margin-top: 50px;
}
.output
{
font-size: 18px;
color: green;
}
</style>
</head>
<body>
<h1>Factorial Calculator</h1>
<p>Enter a number to calculate its factorial</p>
<input type="number" id="factorialInput" placeholder="Enter a number" min="0">
<br><br>
<button onclick="calculateFactorial()">Calculate Factorial</button>
<p id="result" class="output"></p>
<script>
function calculateFactorial()
{
const num = parseInt(document.getElementById('factorialInput').value);
if (isNaN(num) || num < 0)
{
document.getElementById('result').innerText = "Please enter a non-negative number.";
return;
}
let factorial = 1;
for (let i = 1; i <= num; i++)
{
factorial *= i;
}
document.getElementById('result').innerText = `Factorial of ${num} is ${factorial}`;
}
</script>
</body>
</html>

ii. Fibonacci series up to that number


<html>
<head>
<title>Fibonacci Series</title>
<style>
body
{
font-family: 'Times New Roman';
text-align: center;
margin-top: 50px;
}
.output
{
font-size: 18px;
color: green;
}
</style>
</head>
<body>
<h1>Fibonacci Series</h1>
<p>Enter a number to generate Fibonacci series up to that number</p>
<input type="number" id="fibonacciInput" placeholder="Enter a number" min="1">
<br><br>
<button onclick="generateFibonacci()">Generate Fibonacci</button>
<p id="result" class="output"></p>
<script>
function generateFibonacci()
{
const num = parseInt(document.getElementById('fibonacciInput').value);
if (isNaN(num) || num <= 0) {
document.getElementById('result').innerText = "Please enter a positive number.";
return;
}
const series = [0, 1];
while (series[series.length - 1] + series[series.length - 2] <= num) {
series.push(series[series.length - 1] + series[series.length - 2]);
}
document.getElementById('result').innerText = `Fibonacci series: ${series.join(", ")}`;
}
</script>
</body>
</html>

iii . Prime numbers up to that number

<html>
<head>
<title>Prime Numbers</title>
<style>
body
{
font-family: 'Times New Roman';
text-align: center;
margin-top: 50px;
}
.output
{
font-size: 18px;
color: green;
}
</style>
</head>
<body>
<h1>Prime Numbers</h1>
<p>Enter a number to find all prime numbers up to that number</p>
<input type="number" id="primeInput" placeholder="Enter a number" min="2">
<br><br>
<button onclick="findPrimes()">Find Primes</button>
<p id="result" class="output"></p>
<script>
function findPrimes()
{
const num = parseInt(document.getElementById('primeInput').value);
if (isNaN(num) || num < 2)
{
document.getElementById('result').innerText = "Please enter a number greater than or equal
to 2.";
return;
}
const primes = [];
for (let i = 2; i <= num; i++)
{
let isPrime = true;
for (let j = 2; j <= Math.sqrt(i); j++)
{
if (i % j === 0) {
isPrime = false;
break;
}
}
if (isPrime) primes.push(i);
}
document.getElementById('result').innerText = `Prime numbers: ${primes.join(", ")}`;
}
</script>
</body>
</html>

iv. Is it palindrome or not

<html>
<head>
<title>Palindrome Checker</title>
<style>
body
{
font-family: 'Times New Roman';
text-align: center;
margin-top: 50px;
}
.output
{
font-size: 18px;
color: green;
}
.error
{
font-size: 18px;
color: red;
}
</style>
</head>
<body>
<h1>Palindrome Checker</h1>
<p>Enter a number to check if it is a palindrome</p>
<input type="number" id="palindromeInput" placeholder="Enter a number" min="0">
<br><br>
<button onclick="checkPalindrome()">Check Palindrome</button>
<p id="result" class="output"></p>
<script>
function checkPalindrome()
{
const num = document.getElementById('palindromeInput').value;
if (!num || num < 0)
{
document.getElementById('result').innerText = "Please enter a non-negative number.";
document.getElementById('result').className = "error";
return;
}
const reversed = num.split("").reverse().join("");
if (num === reversed)
{
document.getElementById('result').innerText = `${num} is a palindrome!`;
document.getElementById('result').className = "output";
}
else
{
document.getElementById('result').innerText = `${num} is not a palindrome.`;
document.getElementById('result').className = "error";
}
}
</script>
</body>
</html>

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

<html>
<head>
<title>Number Operations</title>
<style>
body
{
font-family: 'Times New Roman';
text-align: center;
margin-top: 50px;
}
.output
{
font-size: 18px;
color: green;
margin-top: 20px;
}
.error
{
font-size: 18px;
color: red;
margin-top: 20px;
}
.buttons
{
margin-top: 20px;
}
button
{
padding: 10px 20px;
margin: 5px;
cursor: pointer;
font-size: 16px;
}
</style>
</head>
<body>
<h1>Number Operations</h1>
<p>Enter a number and choose an operation:</p>
<input type="number" id="numberInput" placeholder="Enter a number" min="0">
<div class="buttons">
<button onclick="calculateFactorial()">Factorial</button>
<button onclick="generateFibonacci()">Fibonacci</button>
<button onclick="findPrimes()">Prime Numbers</button>
<button onclick="checkPalindrome()">Palindrome</button>
</div>
<p id="result" class="output"></p>
<script>
function calculateFactorial()
{
const num = parseInt(document.getElementById('numberInput').value);
if (isNaN(num) || num < 0)
{
displayError("Please enter a non-negative number.");
return;
}
let factorial = 1;
for (let i = 1; i <= num; i++)
{
factorial *= i;
}
displayResult(`Factorial of ${num} is ${factorial}`);
}
function generateFibonacci()
{
const num = parseInt(document.getElementById('numberInput').value);
if (isNaN(num) || num <= 0)
{
displayError("Please enter a positive number.");
return;
}
const series = [0, 1];
while (series[series.length - 1] + series[series.length - 2] <= num)
{
series.push(series[series.length - 1] + series[series.length - 2]);
}
displayResult(`Fibonacci series: ${series.join(", ")}`);
}
function findPrimes()
{
const num = parseInt(document.getElementById('numberInput').value);
if (isNaN(num) || num < 2)
{
displayError("Please enter a number greater than or equal to 2.");
return;
}
const primes = [];
for (let i = 2; i <= num; i++)
{
let isPrime = true;
for (let j = 2; j <= Math.sqrt(i); j++)
{
if (i % j === 0)
{
isPrime = false;
break;
}
}
if (isPrime) primes.push(i);
}
displayResult(`Prime numbers up to ${num}: ${primes.join(", ")}`);
}
function checkPalindrome()
{
const num = document.getElementById('numberInput').value;
if (!num || num < 0)
{
displayError("Please enter a non-negative number.");
return;
}
const reversed = num.split("").reverse().join("");
if (num === reversed)
{
displayResult(`${num} is a palindrome!`);
}
else
{
displayResult(`${num} is not a palindrome.`);
}
}
function displayResult(message)
{
const resultElement = document.getElementById('result');
resultElement.innerText = message;
resultElement.className = "output";
}
function displayError(message)
{
const resultElement = document.getElementById('result');
resultElement.innerText = message;
resultElement.className = "error";
}
</script>
</body>
</html>

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 [email protected])

<html>
<head>
<title>Registration Form Validation</title>
<style>
body
{
font-family: 'Times New Roman';
text-align: center;
margin-top: 50px;
}
form
{
display: inline-block;
text-align: left;
padding: 20px;
border: 1px solid #ccc;
border-radius: 8px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}
.input-group
{
margin-bottom: 15px;
}
.input-group label
{
display: block;
margin-bottom: 5px;
}
.input-group input
{
width: 100%;
padding: 8px;
font-size: 16px;
}
.error
{
color: red;
font-size: 14px;
}
button
{
padding: 10px 20px;
font-size: 16px;
cursor: pointer;
background-color: #28a745;
color: white;
border: none;
border-radius: 4px;
}
button:hover
{
background-color: #218838;
}
</style>
</head>
<body>
<h1>Registration Form</h1>
<form id="registrationForm" onsubmit="return validateForm()">
<div class="input-group">
<label for="name">Name:</label>
<input type="text" id="name" placeholder="Enter your name">
<span id="nameError" class="error"></span>
</div>
<div class="input-group">
<label for="mobile">Mobile:</label>
<input type="text" id="mobile" placeholder="Enter your mobile number">
<span id="mobileError" class="error"></span>
</div>
<div class="input-group">
<label for="email">E-mail:</label>
<input type="text" id="email" placeholder="Enter your email">
<span id="emailError" class="error"></span>
</div>
<button type="submit">Submit</button>
</form>
<script>
function validateForm()
{
let isValid = true;
const name = document.getElementById('name').value;
const nameError = document.getElementById('nameError');
const namePattern = /^[A-Za-z][A-Za-z0-9]{5,}$/;
if (!namePattern.test(name))
{
nameError.innerText = "Name must start with a letter and be at least 6 characters long.";
isValid = false;
}
else
{
nameError.innerText = "";
}
const mobile = document.getElementById('mobile').value;
const mobileError = document.getElementById('mobileError');
const mobilePattern = /^[0-9]{10}$/;
if (!mobilePattern.test(mobile))
{
mobileError.innerText = "Mobile number must be exactly 10 digits.";
isValid = false;
}
else
{
mobileError.innerText = "";
}
const email = document.getElementById('email').value;
const emailError = document.getElementById('emailError');
const emailPattern = /^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$/;
if (!emailPattern.test(email))
{
emailError.innerText = "Enter a valid email address (e.g., [email protected]).";
isValid = false;
}
else
{
emailError.innerText = "";
}
return isValid;
}
</script>
</body>
</html>

You might also like