Adv Java Sol Prev Yr
Adv Java Sol Prev Yr
Group A
1. What are the different data types present in javascript?
Ans: Here are the main data types in JavaScript:
Data
Description Example
Type
Note: It's worth noting that JavaScript is a dynamically typed language, meaning variables can hold
values of any type, and the data type of a variable can change during runtime.
1
a. Getting CSS Properties: You can use the css() method to retrieve the current value of a CSS
property for a selected element. By passing the name of the CSS property as a parameter to css(), you
can obtain its computed value.
b. Setting CSS Properties: The css() method also enables you to set or change CSS properties for the
selected element(s). You can pass an object with key-value pairs representing the properties and their
respective values to be set.
In the example above, the CSS properties background-color, font-size, and color are being set for
all <div> elements selected by the jQuery selector.
Group B
4. a. What is javascript?
Ans: JavaScript is a high-level, interpreted programming language primarily used for client-side web
development. It is one of the three core technologies (HTML, CSS, and JavaScript) of the World Wide
Web and is supported by all modern web browsers. JavaScript allows developers to create interactive
and dynamic elements on web pages, enhance user experience, and build web applications
b. Show how javascript handles onclick(), onmouseover() and onload() events with example.
Ans: Here are examples demonstrating how JavaScript handles the onclick(), onmouseover(), and
onload() events:
1. onclick() Event: The onclick() event is triggered when an element is clicked. It allows you to
specify a function to be executed when the click event occurs. Here's an example that changes
the background color of a <div> element when it is clicked:
<!DOCTYPE html>
<html>
<body>
<div id="myDiv" onclick="changeColor()">Click me!</div>
<script>
function changeColor() {
document.getElementById("myDiv").style.backgroundColor = "red";
}
2
</script>
</body>
</html>
In this example, when the <div> element with the id "myDiv" is clicked, the changeColor()
function is executed. It accesses the element using getElementById() and modifies its
backgroundColor CSS property to "red".
2. onmouseover() Event: The onmouseover() event is triggered when the mouse pointer moves
over an element. It enables you to define a function that executes when the mouse pointer
enters the specified element. Here's an example that changes the text color of a <p> element
when the mouse is over it:
<!DOCTYPE html>
<html>
<body>
<p id="myPara" onmouseover="changeTextColor()">Hover over me!</p>
<script>
function changeTextColor() {
document.getElementById("myPara").style.color = "blue";
}
</script>
</body>
</html>
In this example, when the mouse pointer moves over the <p> element with the id "myPara", the
changeTextColor() function is called. It uses getElementById() to access the element and
modifies its color CSS property to "blue".
3. onload() Event: The onload() event is triggered when a web page or an element finishes
loading. It allows you to specify a function that runs when the page or element has finished
loading. Here's an example that displays an alert when the page finishes loading:
<!DOCTYPE html>
<html>
<body onload="showAlert()">
<script>
function showAlert() {
alert("Page loaded!");
}
</script>
</body>
</html>
3
In this example, the onload attribute is added to the <body> tag. It specifies the showAlert()
function to be executed when the page finishes loading. The showAlert() function displays an
alert box with the message "Page loaded!".
c. Discuss how to do client side validation using javascript.
Ans: Client-side validation refers to the process of validating user input on the client's web
browser before submitting it to the server. JavaScript is commonly used to perform client-side
validation due to its ability to interact with HTML forms and provide immediate feedback to
users. Here's a general approach to implementing client-side validation using JavaScript: Here's a
simplified example that demonstrates client-side validation for a simple login form:
<!DOCTYPE html>
<html>
<head>
<style>
.error {
color: red;
}
</style>
</head>
<body>
<form id="loginForm" onsubmit="validateForm(event)">
<input type="text" id="username" placeholder="Username">
<input type="password" id="password" placeholder="Password">
<button type="submit">Login</button>
</form>
<script>
function validateForm(event) {
event.preventDefault(); // Prevent form submission
// Perform validation
if (username === "") {
displayErrorMessage("username", "Username is required");
}
4
const errorElement = document.createElement("span");
errorElement.classList.add("error");
errorElement.textContent = message;
In this example, the validateForm() function is called when the form is submitted. It checks if
the username and password fields are empty and displays error messages if necessary. The form
is prevented from being submitted if there are validation errors.
By implementing client-side validation using JavaScript, you can provide immediate feedback to
users, reduce server requests for invalid data, and enhance the overall user experience. It is
important to note that client-side validation should be complemented by server-side validation
as well to ensure data integrity and security.
5. a. What is jQuery?
Ans: jQuery is a fast, lightweight, and feature-rich JavaScript library designed to simplify client-side web
development. It provides a wide range of utilities and abstractions, allowing developers to write concise
and efficient code for common tasks, such as DOM manipulation, event handling, AJAX requests, and
animation effects.
jQuery is a widely used JavaScript library that revolutionized web development by simplifying common
tasks and providing a concise and efficient way to interact with web pages. It abstracts away many
complexities of JavaScript and the Document Object Model (DOM), making it easier for developers to
manipulate HTML elements, handle events, perform AJAX requests, and create stunning animations.
With its intuitive and consistent API, jQuery gained popularity for its ability to streamline coding
processes and enhance cross-browser compatibility. It also boasts a vast ecosystem of plugins created
by the community, extending its functionality even further. However, as modern JavaScript has evolved
and native browser APIs have improved, the necessity of jQuery has diminished in some cases. While it
remains a valuable tool for legacy projects and specific use cases, developers now have a wider range
of options to consider, including native JavaScript, other libraries, or popular front-end frameworks.
b. Show the steps of form validation using jQuery with an example.
Ans: Here are the steps to perform form validation using jQuery, along with an example:
Step 1: Include the jQuery Library In the <head> section of your HTML document, include the jQuery
library by adding the following script tag:
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
5
Step 2: Set up the HTML Form Create an HTML form with input fields that require validation. Assign
appropriate IDs or classes to the form and its elements to access them easily using jQuery. Add a
submit button for form submission.
<form id="myForm">
<input type="text" id="name" placeholder="Name">
<input type="email" id="email" placeholder="Email">
<input type="password" id="password" placeholder="Password">
<button type="submit">Submit</button>
</form>
Step 3: Write the jQuery Validation Code In a script tag or external JavaScript file, write the jQuery code
to perform form validation. Use the jQuery selectors to access the form and its elements. Apply
validation rules and conditions using if statements or other jQuery methods.
<script>
$(document).ready(function() {
$("#myForm").submit(function(event) {
event.preventDefault(); // Prevent form submission
// Perform validation
if (name === "") {
alert("Please enter your name");
return;
}
6
In this example, the jQuery code is enclosed in the $(document).ready() function to ensure it
executes when the document is fully loaded. The code attaches a submit event listener to the form with
the ID "myForm". When the form is submitted, the event handler function is triggered.
Within the event handler function, the form input values are retrieved using the jQuery selector
($("#elementId")). The values are then validated against specific conditions. If any validation fails, an
alert message is displayed, and the return statement prevents the form from being submitted. If all
validation passes, a success message is displayed.
Remember to adjust the validation rules and messages according to your specific form requirements.
By following these steps, you can perform form validation using jQuery, providing immediate feedback
to users and ensuring that the submitted data meets the desired criteria.
c. Explain application server services of jQuery.
Ans: The role of jQuery in terms of application server services by using AJAX (Asynchronous JavaScript
and XML).
jQuery simplifies the process of making AJAX requests to the application server and handling the
responses. AJAX allows you to retrieve data from the server without reloading the entire web page,
enabling dynamic and responsive user experiences. Here's how jQuery facilitates this process:
1. AJAX Request Setup: jQuery provides a set of AJAX-related methods, such as $.ajax(),
$.get(), $.post(), etc., which encapsulate the underlying XMLHttpRequest functionality. These
methods allow you to configure the AJAX request, including the URL, request type (GET, POST,
PUT, DELETE), data to be sent, headers, and more.
2. Sending AJAX Requests: With jQuery, you can easily send AJAX requests to the application
server by specifying the appropriate method ($.get(), $.post(), etc.) and providing the
required parameters. This process involves specifying the URL endpoint to which the request is
sent, along with any additional data to be included in the request payload.
3. Handling Server Responses: jQuery provides convenient methods to handle the server's
response to the AJAX request. You can use the .done() method to specify a callback function
that executes when the request succeeds, allowing you to process and manipulate the returned
data. Similarly, you can use the .fail() method to handle errors or failures that may occur
during the AJAX request.
4. DOM Manipulation and UI Updates: Once the server response is received, jQuery allows you to
manipulate the Document Object Model (DOM) to update the web page dynamically. You can
modify HTML elements, change styles, insert new content, or perform any other necessary DOM
manipulation to reflect the data retrieved from the server. This enables seamless updates to the
user interface without a full page reload.
By leveraging jQuery's AJAX capabilities, you can interact with the application server, fetch data, submit
form data, update server-side resources, and handle the responses asynchronously. This enables you to
create more interactive and responsive web applications, enhancing the user experience.
d. Give an example using jQuery.length.
Ans: Certainly! The length property in jQuery allows you to retrieve the number of elements that
match a specific selector or are part of a jQuery object. Here's an example that demonstrates the usage
of length:
7
<!DOCTYPE html>
<html>
<head>
<title>jQuery length Example</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<div class="container">
<p>Hello, World!</p>
<p>How are you?</p>
<p>Have a nice day!</p>
</div>
<script>
$(document).ready(function() {
var paragraphs = $("p"); // Select all <p> elements
var paragraphCount = paragraphs.length;
In this example, we have a simple HTML document that contains three <p> elements within a <div
class="container"> element. We use the jQuery selector $("p") to select all the <p> elements on
the page.
The length property is then used on the paragraphs variable, which represents the jQuery object
containing the selected <p> elements. By accessing paragraphs.length, we retrieve the number of
<p> elements matched by the selector.
In the example, the value of paragraphCount will be 3 since there are three <p> elements on the page.
We log this value to the console using console.log().
You can run this example in a web browser and open the developer console to see the output. It
demonstrates how length can be used to determine the count of elements matched by a selector
using jQuery.
8
2022
Group A
1) Write down the advantages and disadvantages of javascript.
Ans:
Advantages Disadvantages
1. Versatility: JavaScript can be used for both client- 1. Browser Compatibility: JavaScript may behave
side and server-side development, making it a differently across different browsers, requiring
versatile language. additional testing and optimization.
3. Rich Ecosystem: JavaScript has a vast ecosystem 3. No Static Typing: JavaScript is dynamically
with numerous libraries, frameworks (e.g., React, typed, which can lead to potential runtime errors
Angular), and tools, enabling rapid development. and difficulties in code maintenance.
6. Easy Learning Curve: JavaScript has a relatively 6. Limited File Access: Due to security
gentle learning curve, making it accessible for restrictions, JavaScript has limited access to the
beginners and quick to start developing. user's file system.
1
Method Description Effects
All three methods affect the DOM structure, but they differ in terms of the permanence of the removal
and the retention of data and event handlers.
empty() is useful when you want to remove the content of an element but keep the element itself. It's
commonly used to clear out the contents of form fields or remove the contents of a container element.
remove() is used to completely remove elements from the DOM, including all child elements. It is
helpful when you want to permanently delete elements from the page and free up memory.
detach() is similar to remove(), but it keeps the detached elements and their associated data in
memory. This method is useful when you want to temporarily remove elements and later reinsert them
back into the DOM without losing their data or event handlers.
Remember that all these methods can be used with selectors to target specific elements or groups of
elements within the DOM.
The significance of the length property lies in its usefulness for conditionally checking the presence or
absence of elements. Here are a few examples:
1. Checking for Existence: By checking the length property, you can determine if any elements match a
given selector. For example:
if ($('p').length > 0) {
// Do something if at least one <p> element exists
}
2
This allows you to conditionally execute code based on the presence or absence of certain elements in the
DOM.
2. Iterating over Elements: You can use the length property in a loop to iterate over a set of elements. For
instance:
$('li').each(function(index) {
console.log('Item ' + index + ': ' + $(this).text());
});
Here, the length property helps determine the number of elements matched by the 'li' selector, allowing
you to loop through each element.
3. Validation and Error Handling: The length property is often used in form validation scenarios. For
instance, you can check if any input fields are empty before submitting a form:
if ($('input[type="text"]').length === 0) {
// Display an error message if no text inputs are found
}
This can help ensure that required fields are filled before proceeding.
In summary, the length property in jQuery is significant as it allows you to determine the number of elements
matched by a selector, enabling you to perform conditional checks, iterate over elements, and handle
validation scenarios effectively.
In JavaScript, you can declare and initialize an array using the following syntax:
3
1. Array Literal Syntax: You can declare an array using square brackets [] and separate the elements
with commas. For example:
In this example, an array named fruits is declared and initialized with three string elements.
2. Array Constructor: You can use the Array constructor to create an array. You can pass the elements as
arguments to the constructor or provide a single numeric argument representing the length of the
array. For example:
The first example creates an array named numbers with five numeric elements. The second example creates an
empty array named emptyArray.
3. Array.from(): The Array.from() method creates a new array from an iterable object or an array-like
object. For example:
In this example, myArray is created from the iterable string "hello" and contains each character as a separate
element.
4. Array.of(): The Array.of() method creates a new array with the provided elements as its elements.
For example:
It's important to note that arrays in JavaScript are dynamic, meaning their length can change, and they can
hold elements of different types. You can access and modify array elements using their indexes, starting from
0.
These are some common ways to declare arrays in JavaScript, and you can choose the one that suits your
specific use case or coding style.
Group B
4) a. Explain different jQuery selectors with example.
Ans
4
Selector Description Example
Selects elements that are $('h1 + p') selects the <p> element immediately
Sibling
siblings of another element. following an <h1> element.
Selects even-indexed
:even elements (0-based) within a $('tr:even') selects even-indexed <tr> elements.
set.
Selects odd-indexed
:odd elements (0-based) within a $('tr:odd') selects odd-indexed <tr> elements.
set.
Note: In the examples above, the selectors are used within the $() function, which is the jQuery selector
syntax.
5
b. Write code snippet in jQuery to implement blur() and hover() method.
Ans Certainly! Below is a code snippet that demonstrates the use of the blur() and hover() methods in
jQuery:
$(document).ready(function() {
// blur() method example
$('input').blur(function() {
$(this).css('background-color', 'white');
});
The blur() method is used to handle the blur event on input elements. When an input element loses
focus (i.e., when the user clicks outside the input field), the background color of that input element is
changed to white.
The hover() method is used to handle the mouseenter and mouseleave events on elements with the
class "box". When the mouse enters a "box" element, it adds the "highlight" class, and when the mouse
leaves, it removes the "highlight" class.
Make sure to include the jQuery library in your HTML file before using this code snippet. You can either
download jQuery and include it locally or use a CDN (Content Delivery Network) version. For example:
<!DOCTYPE html>
<html>
<head>
<title>jQuery Blur and Hover Example</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<style>
.highlight {
background-color: yellow;
}
</style>
</head>
<body>
<input type="text" placeholder="Blur Example">
<div class="box">Hover Example</div>
</body>
</html>
6
In the above example, when the input field loses focus, its background color will change to white. Additionally,
when you hover over the "box" div, it will be highlighted with a yellow background.
5) a. Write a program in javascript that push elements in an array dynamically and display the array in
both reversed and sorted order.
Ans Program in JavaScript that allows the user to dynamically push elements into an array and then displays
the array in both reversed and sorted order:
function pushElement() {
var element = prompt('Enter an element to add to the array:');
array.push(element);
displayArray();
}
function displayArray() {
console.log('Array:', array);
console.log('Reversed Array:', array.slice().reverse());
console.log('Sorted Array:', array.slice().sort());
}
In this program:
To test the program, you can call the pushElement() function multiple times in the browser console or add a
button to your HTML and attach an event listener to it.
<!DOCTYPE html>
<html>
<head>
<title>Dynamic Array</title>
<script>
var array = [];
function pushElement() {
var element = prompt('Enter an element to add to the array:');
array.push(element);
displayArray();
}
7
function displayArray() {
console.log('Array:', array);
console.log('Reversed Array:', array.slice().reverse());
console.log('Sorted Array:', array.slice().sort());
}
</script>
</head>
<body>
<button onclick="pushElement()">Add Element</button>
</body>
</html>
By clicking the "Add Element" button, a prompt will appear to enter an element. After each entry, the array,
reversed array, and sorted array will be displayed in the browser console.
- Click event: Triggers when a mouse - Add event handlers to the respective
button is clicked on an element. HTML element or form.
- Form submission event: Triggers when a - Assign a function or call a function to
Event
form is submitted. execute when the event occurs.
- Mouse out event: Triggers when the - The function can be defined inline or
mouse pointer leaves an element. referenced by name.
It's important to note that these event handlers can also be assigned using the addEventListener() method
or by using the on prefix with the respective event name (e.g., element.onclick, element.onsubmit,
element.onmouseout).
<!DOCTYPE html>
<html>
<head>
<title>Event Handling Example</title>
<script>
function handleClick() {
console.log('Element clicked!');
8
}
function handleSubmit() {
console.log('Form submitted!');
}
function handleMouseOut() {
console.log('Mouse pointer left the element!');
}
</script>
</head>
<body>
<button onclick="handleClick()">Click Me</button>
<form onsubmit="handleSubmit()">
<input type="text" name="username" placeholder="Username">
<input type="password" name="password" placeholder="Password">
<input type="submit" value="Submit">
</form>
In the above example, when you click the "Click Me" button, the handleClick() function is executed, logging
a message to the console. Similarly, when the form is submitted or the mouse pointer leaves the div, the
respective functions (handleSubmit() and handleMouseOut()) are called, and their messages are logged to
the console.
First, include the jQuery library and the jQuery Validation plugin in your HTML file:
<!DOCTYPE html>
<html>
<head>
<title>Form Validation Example</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script
src="https://cdn.jsdelivr.net/jquery.validation/1.16.0/jquery.validate.min.js">
</script>
</head>
<body>
<!-- Your form goes here -->
</body>
</html>
9
Then, define your form and validation rules, including custom error messages, using the plugin's validate()
method:
$(document).ready(function() {
$('#myForm').validate({
rules: {
username: {
required: true,
minlength: 5
},
email: {
required: true,
email: true
},
password: {
required: true,
minlength: 8
}
},
messages: {
username: {
required: "Please enter a username",
minlength: "Username must be at least 5 characters long"
},
email: {
required: "Please enter an email address",
email: "Please enter a valid email address"
},
password: {
required: "Please enter a password",
minlength: "Password must be at least 8 characters long"
}
}
});
});
We use the validate() method on the form element with the ID myForm.
The rules object defines the validation rules for each form field. In this example, the username field is
required and must have a minimum length of 5 characters, the email field is required and must be a
valid email address, and the password field is required and must have a minimum length of 8
characters.
The messages object provides custom error messages for each form field. You can customize the error
messages for different validation rules.
10
<form id="myForm" method="post">
<label for="username">Username:</label>
<input type="text" id="username" name="username">
<br>
<label for="email">Email:</label>
<input type="email" id="email" name="email">
<br>
<label for="password">Password:</label>
<input type="password" id="password" name="password">
<br>
With this setup, the form inputs will be validated based on the specified rules, and custom error messages will
be displayed when the validation fails.
Note: Make sure to place the JavaScript code inside a $(document).ready() function to ensure it runs after
the document is fully loaded.
11