Web Technology · Unit 4 · 9 hrs
Client Side Scripting with JavaScript
Exam-focused notes for Client Side Scripting with JavaScript (Web Technology, CSC329): what the TU syllabus asks and how it has actually been tested, with 16 solved past questions from this unit.
Client Side Scripting with JavaScript in short
JavaScript is what turns a static page into an interactive one, running directly in the visitor's browser to react to input, change the page on the fly, and talk to a server in the background. This unit builds up the language from its basic syntax to the DOM, events, jQuery and JSON.
What this unit covers
- Structure of JavaScript Program
- Variables and Data Types
- Statements: Expression, Keyword, Block
- Operators
- Flow Controls
- Looping
- Functions
- Popup Boxes: Alert, Confirm, Prompt
- Objects and properties
- Constructors
- Arrays
- Built-in Objects: Window, String, Number, Boolean, Date, Math, RegExp, Form, DOM
- User Defined Objects
- Event Handling and Form Validation
- Error Handling
- Handling Cookies
- jQuery Syntax
- jQuery Selectors
- Events and Effects
- Introduction to JSON
jQuery Selectors
2082 · 10 marks
What are jQuery selectors? Explain jQuery callback and chaining effects with appropriate jQuery scripts.[10]
Show solved answerHide answer
jQuery Selectors, Callback, and Chaining Effects
1. jQuery Selectors
jQuery selectors allow us to select and manipulate HTML elements. They are used to "find" (or select) HTML elements based on their name, id, class, attributes, and more.
All selectors in jQuery start with the dollar sign and parentheses:
$()
Types of jQuery Selectors
| Selector | Description | Example |
|---|---|---|
| Element Selector | Selects elements based on element name | $("p") selects all <p> elements |
| ID Selector | Selects a single element with a specific id | $("#myId") |
| Class Selector | Selects all elements with a specific class | $(".myClass") |
| Universal Selector | Selects all elements | $("*") |
| this Selector | Refers to the current HTML element | $(this) |
Example of Element Selector
$(document).ready(function() {
$("button").click(function() {
$("p").hide();
});
});
When a user clicks the button, all <p> elements will be hidden.
2. jQuery Callback
A callback function is a function that is executed after the current effect is fully finished. This is important because jQuery effects take time (e.g., slow, fast, milliseconds), and without a callback, the next line of code may run before the effect completes.
Syntax
$(selector).hide(speed, callback);
speed- optional; can be"slow","fast", or millisecondscallback- optional; the function to execute after the effect completes
Example of Callback
$("button").click(function() {
$("p").hide("slow", function() {
alert("The paragraph is now hidden");
});
});
Explanation:
- When the button is clicked, the
<p>element hides slowly. - Only after the hide effect is completely finished, the
alert()callback function executes. - Without the callback, the alert might fire before the hiding animation completes.
Another Callback Example with fadeIn
$("button").click(function() {
$("p").fadeIn(1000, function() {
alert("Fade In complete!");
});
});
3. jQuery Chaining
Chaining allows us to run multiple jQuery methods/commands one after another on the same element(s) in a single statement. This makes code shorter and more efficient.
To chain an action, we simply append the action to the previous action.
Syntax
$(selector).method1().method2().method3();
Example of Chaining
$("button").click(function() {
$("#div").css("color", "red").slideUp(200).slideDown(200);
});
Explanation of the above example:
css("color", "red")- changes the text color of#divto red.slideUp(200)- slides the element up in 200 milliseconds.slideDown(200)- slides the element back down in 200 milliseconds
All three methods are applied to the same element #div one after another.
Another Chaining Example
$(document).ready(function() {
$("button").click(function() {
$("p")
.css("color", "blue")
.fadeOut(1000)
.fadeIn(1000);
});
});
Explanation:
- The
<p>element first turns blue. - Then it fades out over 1 second.
- Then it fades back in over 1 second.
Summary Table
| Feature | Description | Key Benefit |
|---|---|---|
| Selectors | Find/select HTML elements by name, id, class | Easy DOM access |
| Callback | Function executed after an effect finishes | Ensures sequential execution |
| Chaining | Multiple methods applied to same element in one line | Shorter, cleaner code |
Note: jQuery follows the syntax
$(selector).action()where$grants access to jQuery,selectorfinds HTML elements, andaction()performs operations on them.
2078 · 5 marks
How jQuery id selector can be used to select specific element? Write an example with jQuery that will hide a paragraph on clicking a button. [5]
Popup Boxes
2082 · 5 marks
Write an HTML script with proper JavaScript that will take an input from prompt box and display the input as output using the alert box. [5]
Built-in Objects
2082 · 5 marks
What is the use of alert box? Write a JavaScript program to show the use of RegExp object. [5]
Show solved answerHide answer
Alert Box and JavaScript RegExp Object
Alert Box
An alert box is a built-in JavaScript dialog box used to display a message or information to the user. It shows a popup window with a message and an OK button. The user must click OK to proceed.
Uses of Alert Box:
- To display important information or warnings to the user
- To show validation error messages
- To debug JavaScript code by displaying variable values
- To notify the user about the result of an operation
Syntax:
alert("Your message here");
RegExp Object in JavaScript
A RegExp (Regular Expression) object is used to match character combinations in strings. It is used for pattern matching and text searching/replacing.
Syntax:
var pattern = new RegExp("pattern", "flags");
// OR shorthand
var pattern = /pattern/flags;
Common Flags:
| Flag | Description |
|---|---|
i | Case-insensitive matching |
g | Global match (find all matches) |
m | Multiline matching |
Common Methods:
| Method | Description |
|---|---|
test() | Returns true or false if pattern matches |
exec() | Returns matched result or null |
JavaScript Program Using RegExp Object
<!DOCTYPE html>
<html>
<head>
<title>RegExp Object Example</title>
</head>
<body>
<h2>RegExp Object Demo</h2>
<form>
<label>Enter Username:</label>
<input type="text" id="username" />
<label>Enter Password:</label>
<input type="text" id="password" />
<input type="button" value="Validate" onclick="validate()" />
</form>
<script type="text/javascript">
function validate() {
var uname = document.getElementById("username").value;
var pwd = document.getElementById("password").value;
// Username: only letters and digits, minimum 5 characters
var unamePattern = new RegExp("^[a-zA-Z0-9]{5,}$");
// Password: must start with a digit and end with $
var pwdPattern = /^\d.*\$$/;
// Validate username
if (!unamePattern.test(uname)) {
alert("Invalid username! Username must be at least 5 characters"
+ " and contain only letters or digits.");
return;
}
// Validate password
if (!pwdPattern.test(pwd)) {
alert("Invalid password! Password must start with a digit"
+ " and end with '$'.");
return;
}
alert("Validation Successful! Welcome, " + uname);
}
</script>
</body>
</html>
Explanation of Patterns Used
| Pattern | Meaning |
|---|---|
^[a-zA-Z0-9]{5,}$ | Username starts (^) and ends ($) with alphanumeric characters, minimum 5 |
^\d.*\$$ | Password starts (^) with a digit (\d), has any characters (.*), and ends with $ |
test() | Returns true if the string matches the pattern, false otherwise |
Note: The
alert()box is used here to display validation messages, demonstrating both the use of alert boxes and the RegExp object together.
2080 · 5 marks
How HTML elements are accessed using getElementById and getElementByTagName, illustrate using HTML script. [5]
Event Handling and Form Validation
2081 · 10 marks
Create an HTML file containing form with textbox, select and radio button. Now write a javascript function for validating the form elements. Validate textbox for required, select field should have some value selected and radio button should be checked.[10]
2080 · 10 marks
Write HTML script to create HTML form as below and perform form validation using JavaScript. The validation should be as; the username should be of length at least 4 and is required. The password should start with a character and end with # and is required. The country and gender should be checked.[10]
2079 · 10 marks
Create an HTML file containing form elements textbox for username, password field and a checkbox for hobbies. Now write javascript function for the form validation. You should validate for username to be empty, password should be of length at least 5, and the check box should be checked.[10]
Show solved answerHide answer
HTML Form Validation - Username, Password, and Checkbox
Complete HTML File with JavaScript Validation
<!DOCTYPE html>
<html>
<head>
<title>Form Validation</title>
</head>
<body>
<h2>Registration Form</h2>
<form name="myForm" onsubmit="return validate()">
<!-- Username Field -->
<label for="username">Username:</label>
<input type="text" id="username" name="username">
<!-- Password Field -->
<label for="password">Password:</label>
<input type="password" id="password" name="password">
<!-- Hobbies Checkbox -->
<label>Hobbies:</label>
<input type="checkbox" id="reading" name="hobbies" value="reading"> Reading
<input type="checkbox" id="gaming" name="hobbies" value="gaming"> Gaming
<input type="checkbox" id="coding" name="hobbies" value="coding"> Coding
<!-- Submit Button -->
<input type="submit" value="Submit">
</form>
<script type="text/javascript">
function validate() {
// ---- 1. Username Validation (should not be empty) ----
var username = document.getElementById("username").value;
if (username === "") {
alert("Username cannot be empty. Please enter your username.");
return false;
}
// ---- 2. Password Validation (length at least 5) ----
var password = document.getElementById("password").value;
if (password === "") {
alert("Password cannot be empty. Please enter your password.");
return false;
}
if (password.length < 5) {
alert("Password must be at least 5 characters long.");
return false;
}
// ---- 3. Checkbox Validation (at least one must be checked) ----
var hobbies = document.getElementsByName("hobbies");
var isChecked = false;
for (var i = 0; i < hobbies.length; i++) {
if (hobbies[i].checked) {
isChecked = true;
break;
}
}
if (!isChecked) {
alert("Please select at least one hobby.");
return false;
}
// All validations passed
alert("Form submitted successfully!");
return true;
}
</script>
</body>
</html>
Explanation of Each Part
1. Form Structure
| Element | Type | Purpose |
|---|---|---|
<input type="text"> | Text box | Accepts username input |
<input type="password"> | Password field | Accepts password (masked) |
<input type="checkbox"> | Checkbox | Allows hobby selection |
onsubmit="return validate()" | Event handler | Calls validation before submit |
Note: The
onsubmitevent handler calls thevalidate()function. If the function returnsfalse, the form is NOT submitted. This is standard client-side validation.
2. Validation Logic Summary
Username Validation:
if (username === "") {
alert("Username cannot be empty.");
return false;
}
- Checks if the username field is left blank.
- Returns
falseto stop form submission.
Password Validation:
if (password.length < 5) {
alert("Password must be at least 5 characters long.");
return false;
}
- First checks if empty, then checks minimum length of 5.
Checkbox Validation:
for (var i = 0; i < hobbies.length; i++) {
if (hobbies[i].checked) {
isChecked = true;
break;
}
}
if (!isChecked) {
alert("Please select at least one hobby.");
return false;
}
- Uses
getElementsByName()to get all checkboxes with name"hobbies". - Loops through each checkbox to check if at least one is selected.
- If none is checked, shows alert and returns
false.
3. Flow Diagram
User clicks Submit
|
v
Username empty? --> YES --> Alert + return false (stop)
|
NO
|
v
Password empty? --> YES --> Alert + return false (stop)
|
NO
|
v
Password length < 5? --> YES --> Alert + return false (stop)
|
NO
|
v
Any checkbox checked? --> NO --> Alert + return false (stop)
|
YES
|
v
Form submitted successfully (return true)
2078 · 10 marks
Create an HTML signup form with fields Name, Email, Password, and Age. Validate the form using JavaScript. Write functions for validating each of the elements. All of the fields should not be empty. The Email address should be a valid email, the password should be of length at least 6 and should start with the alphabet and end with a digit. The age should be between 8 and 60.[10]
Arrays
2081 · 5 marks
How can you define array in javascript? Create an array Fruit with its elements 'apple', 'banana', 'mango', 'grape' and print the array. [5]
Events and Effects
2080 · 5 marks
What is chaining in jQuery? Write a script to illustrate concept of chaining using slideUp and slideDown method. [5]
Show solved answerHide answer
Chaining in jQuery
Definition
Chaining allows us to run multiple jQuery commands, one after another, on the same element(s) in a single statement. To chain an action, we simply append the action to the previous action using the dot (.) operator. This makes the code shorter, cleaner, and more efficient because jQuery does not need to find the same element multiple times.
General Syntax:
$(selector).method1().method2().method3();
Script Illustrating Chaining using slideUp() and slideDown()
<!DOCTYPE html>
<html>
<head>
<title>jQuery Chaining Example</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<style>
#myDiv {
width: 200px;
height: 100px;
background-color: lightblue;
padding: 10px;
font-size: 18px;
}
</style>
</head>
<body>
<h2>jQuery Chaining Demo</h2>
<div id="myDiv">This is a div element.</div>
<button id="btn">Click to Chain Effects</button>
<script>
$(document).ready(function() {
$("#btn").click(function() {
$("#myDiv")
.css("color", "red")
.slideUp(1000)
.slideDown(1000);
});
});
</script>
</body>
</html>
Explanation of the Script
| Step | Code | Description |
|---|---|---|
| 1 | .css("color", "red") | Changes the text color of #myDiv to red |
| 2 | .slideUp(1000) | Slides the #myDiv element up (hides it) over 1000 milliseconds |
| 3 | .slideDown(1000) | Slides the #myDiv element down (shows it) over 1000 milliseconds |
All three methods are chained together on the same element (#myDiv) in a single statement. jQuery executes them one after another in sequence.
Key Benefit
Without chaining, the same code would require three separate lines each finding #myDiv:
// Without chaining (less efficient)
$("#myDiv").css("color", "red");
$("#myDiv").slideUp(1000);
$("#myDiv").slideDown(1000);
With chaining, it is written in one clean statement, which is more readable and performs better.
2079 · 5 marks
Describe the jQuery Animate() method. Write an html script to create a div with id 'mydiv'. The position of the div should be set to absolute. Now show the use of animate method to the div element to right by 300px. [5]
2076 · 5 marks
How jQuery animate can be used to create custom animation? Write syntax with sample script. [5]
Introduction to JSON
2076 · 5 marks
What is the use of JSON? How can you parse a JSON, illustrate with an example. [5]
Objects and properties
2076 · 10 marks
How can you create objects in Javascript? Create a HTML page containing a division with image and its description in paragraph. Write a javascript function to change the value of description in the paragraph during onmouseover and mouseout event on the image.[10]
Make Unit 4 stick
Practice CSC329 with flashcards & quizzes