Important Programs With Solutions
Important Programs With Solutions
function cube(c)
{
var cb=c*c*c;
return cb;
}
</script> </head></html>
===DATE FUNCTIONS===
===DATE FUNCTIONS===
(1) By default, JavaScript will use the browser's time zone and display a date
as a full text string:
<html><body>
<h2>Using new Date()</h2>
<p id="demo"></p>
<script>
const d = new Date();
document.getElementById("demo").innerHTML = d;
//or
document.write(d);
</script></body></html>
(3) Same as above but display date, month, year, hour, minutes, seconds
separately
<html> <body>
<h3>Using new Date()</h3>
<script>
const now = new Date();
document.write("<br>Current date and time: " + now);
document.write("<br>Year: " + now.getFullYear()); // Get current year
document.write("<br>Month: " + (now.getMonth() + 1)); // Get the current month
(0-11, so +1)document.write("<br>Day: " + now.getDate()); // Get the current day
document.write("<br>Hours: " + now.getHours()); // Get current hours
document.write("<br>Minutes: " + now.getMinutes()); // Get current minutes
document.write("<br>Seconds: " + now.getSeconds()); // Get current seconds
</script> </body> </html>
(4) Same as above but display date, month, year as: dd/mm/yyyy
And hour, minutes, seconds as: hh:mm:ss
<html>
<body>
<h3>Using new Date()</h3>
<script>
var now = new Date();
document.write("<br>" + now);
y=now.getFullYear();
m=(now.getMonth() + 1); d=now.getDate();
document.write("<br><br><B> Today's date:"+d+"/"+m+
"/"+y);
h=now.getHours();
min=now.getMinutes();
sec=now.getSeconds();
document.write("<br><br><b>" +h+":"+min+":"+sec);
</script> </body> </html>
ARRAY FUNCTIONS
The reduce() method takes an array and reduces it to a single value by applying a function (like addition) to each
element in the array.
How reduce() works:
1. It starts with an initial value (in this case, 0).
2. It iterates over the array, applying a function that takes two arguments:
o acc (accumulator): This is the running total, which starts with the initial value.
o curr (current value): This is the current element of the array during each iteration.
3. It updates the accumulator with the result of the function applied to the current element.
Explaination:
num => num > 10:
num is just a temporary name (a placeholder) that represents each number in the numbers array.
As find() goes through the array, it looks at each number one by one, and for each number, it temporarily
assigns that value to num.
Condition (num > 10): The part after the => is a condition that checks if the current number (represented
by num) is greater than 10.
2) Accessing all ements of an Array
3) To display Duplicate enteries in array and then Unique numbers from an Array
<html><head><title>Remove Duplicates</title></head>
<body>
<script>
// Array with duplicates
var nums = [1, 2, 2, 3, 4, 4, 5];
// To display original array with duplicate values:
document.write("Original Array Content=>");
for(var i=0; i<nums.length; i++)
{
document.write(nums[i]+",");
}
// Array to hold unique numbers
var unique = [];
VALIDATIONS
// Name validation
if (name === "") {
result += "Name cannot be empty.<br>";
} else {
result += "Name is valid.<br>";
}
// Password validation
if (password === "") {
result += "Password cannot be empty.<br>";
} else if (password.length < 6) {
result += "Password must be at least 6 characters long.<br>";
} else {
result += "Password is valid.<br>";
}
// Age validation
if (age === "") {
result += "Age cannot be empty.<br>";
} else if (age < 18) {
result += "You must be 18 or older.<br>";
} else {
result += "Age is valid.<br>";
}
document.getElementById('result').innerHTML = result;
}
</script> </body> </html>
the regex ^[^ ]+@[^ ]+\.[a-z]{2,3}$ checks if a given string matches the general structure of an email address.
Specifically, it verifies that:
The email starts with one or more characters (excluding spaces).
It contains an @ symbol.
It follows with one or more characters (excluding spaces).
It includes a . (dot).
It ends with a TLD that is 2 to 3 lowercase letters.
Example Matches
Valid Emails:
o [email protected]
o [email protected]
o [email protected]
<h3>Validation Results:</h3>
<div id="result"></div>
<script>
function validateForm() {
const name = document.getElementById('name').value;
const email = document.getElementById('email').value;
const password = document.getElementById('password').value;
const confirmPassword = document.getElementById('confirmPassword').value;
const age = document.getElementById('age').value;
// Name validation
if (name === "") {
result += "Name cannot be empty.<br>";
} else {
result += "Name is valid.<br>";
}
// Password validation
if (password === "") {
result += "Password cannot be empty.<br>";
} else if (password.length < 6) {
result += "Password must be at least 6 characters long.<br>";
} else {
result += "Password is valid.<br>";
}
// Age validation
if (age === "") {
result += "Age cannot be empty.<br>";
} else if (age < 18) {
result += "You must be 18 or older.<br>";
} else {
result += "Age is valid.<br>";
}
document.getElementById('result').innerHTML = result;
}
</script></body></html>
EVENT HANDLING
<script>
function sum()
{
var a=10, b=20,c=0;
c=a+b;
alert("Sum:"+c);
}
function sub()
{
var a=10, b=20,c=0;
c=b-a;
alert("Subtraction:"+c);
}
function mm(btn)
{
btn.style.backgroundColor = "cyan"; }
</script>
</body></html>
Window Events
== Progam on Window methods: Alert, Prompt, Confirm, open, close
<html>
<body onload='alert("JavaScript window Event Handling")'>
<input type="button" value="New Window" onclick="window.open('js2.html', 'login',
'width=250,height=200')">
<!-- This won't close the main window but would work for windows opened via JavaScript -->
<input type="button" value="Close" onclick="window.close()">
</body>
</html>
In the window.open function, the second parameter 'login' is the name of the new window you
are opening. It acts like an identifier for the new window. Here's what it does:
If you open multiple windows using the same name ('login'), each new call to
window.open with that name will reuse the same window instead of opening a new one.
You can give it any meaningful name or leave it empty ('') if you don't need to reference
the window later.
Most modern browsers have restrictions on closing windows. A window can only be closed by
window.close() if:
1. It was opened by JavaScript (e.g., using window.open()).
2. You can't close a window that wasn't opened using window.open() (like the main window
or windows opened manually by the user).
DOM
DOM (Document Object Model) operations in JavaScript allow us to interact with and manipulate the
structure, style, and content of web pages. Let's go through some common DOM operations, with a
simple example to illustrate each operation:
<script>
// Access the Element by ID
var title = document.getElementById('h1title');
document.write ("Accessing Heading 1 contents::<br>"+title.textContent);
//title.textContent accesses the text inside the paragraph element.
</script> </body> </html>
3) To modify content of any element, here example-h1(Modifying
Elements)
<html> <head>
<title>Modifying Content Example</title> </head>
<body>
<h1 id="h1title">Welcome to JavaScript!!!</h1>
<script>
// Access the h1 element by ID
var title = document.getElementById('h1title');
Explanation: Using style.color property to change the colour of <h1> to "blue" colour.
7) To use event handler when button is clicked ( Handling Events)
<html><head> <title>Handling Events Example</title></head>
<body>
<button id="my-button">Click Me!</button>
<script>
// Use of event listener on the Button click
var button = document.getElementById('my-button');
button.addEventListener('click', function() {
alert('Button was clicked!');
});
</script> </body> </html>
try {
// Check if the input is a valid number
if (isNaN(userInput) || userInput.trim() === "") {
throw new Error("Invalid input! Please enter a valid number.");
}
Step 4:
Access the Program
Open your web browser.
Go to http://localhost:8000
Click the "Load Data" button and text from data.txt displayed on the page.
File 1: Index.html
<html> <head>
<title>AJAX Example</title>
<script>
function loadData() {
var xhr = new XMLHttpRequest();
xhr.open('GET', 'data.txt', true);
xhr.onload = function ()
{
if (xhr.status === 200)
{
document.getElementById('content').innerText = xhr.responseText;
}
else
{
document.getElementById('content').innerText = 'Error loading data';
}
};
xhr.send();
}
</script> </head>
<body>
<h1>AJAX Example</h1>
<button onclick="loadData()">Load Data</button>
<p id="content">Data will appear here...</p>
</body> </html>
File 2: Data.txt
Hello, this is data fetched using AJAX!
Output:
Explanation:
var xhr = new XMLHttpRequest(); : a new XMLHttpRequest object named xhr is
created, which allows us to send and receive data from a server.
xhr.onreadystatechange = function() { ... }: This sets up a function that will run
whenever the readyState of xhr changes. The readyState tells us what stage the
request is in.
if (xhr.readyState === 4 && xhr.status === 200) { ... }: This checks if the request
is complete (readyState === 4) and was successful (status === 200). If both
conditions are true, it means we got a valid response from the server.
document.getElementById("result").innerText = xhr.responseText;: This line
updates the paragraph with the ID result to show the data we received from the
server (stored in xhr.responseText).
xhr.open("GET", "data.txt", true);: This prepares the request. We specify that we
want to send a GET request to data.txt . The true means we want to perform the
request asynchronously
xhr.send(): This sends the request to the server.
document.getElementById("loadButton").onclick = loadData;: This sets up an
event listener for the button. When the button is clicked, it calls the loadData
function to load the data.
When the data is successfully fetched, it is displayed in the paragraph with the ID result.
To practice:
1. Create a function using the “function” keyword that takes a String as an argument & returns the
number of vowels in the string. Create an array function to perform the same task
2- For a given array of numbers, print the square of each value using the forEach loop.
3- We are given array of marks of students. Filter out of the marks of students that scored 90+.
4- For a given array with marks of students -> [85, 97, 44, 37, 76, 60]. Find the average marks of the
entire class.
5- Create an array to store companies -> “Bloomberg” , “Microsoft” , “Uber” , “Google” , “IBM” ,
“Netflix” a. Remove the first company from the array b. Remove Uber & Add Ola in its place c. Add
Amazon at the end.
6- Get user to input a number using prompt(“Enter a number: ”). Check if the number is a multiple of
5 or not
7- Write a code which can give grades to students according to their scores:
80-100, A
70-89, B
60-69, C
50-59, D
0-49, F
8- Write a program to implement a basic AJAX request where the client sends a name to the server,
and the server responds with a greeting message.
9- Write a program to submit a form using AJAX, where the data is sent to the server, and the response
(e.g., "Form submitted successfully!") is displayed without refreshing the page.
OR
Implement a file upload feature using AJAX. The user should be able to upload an image without
reloading the page, and the uploaded image should be displayed on the page once the upload is
successful.