4 Client Side Scripting With Javascript

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.

Client Side Scripting with JavaScript: notes

Structure of JavaScript Program

A JavaScript program is a list of statements executed by the browser's JavaScript engine. Script files carry the .js extension and are attached to an HTML page with a <script> element; when the src attribute is used, the file's own code is not written between the tags. Placing <script> in <head> runs it before the page body exists, so scripts that touch the page's content are usually placed just before </body>, or deferred, so the HTML they depend on has already loaded.

<!DOCTYPE html>
<html>
<head>
  <title>My Web Page</title>
</head>
<body>
  <h1>Page heading</h1>
  <p>Page content</p>
  <script src="file.js"></script>
</body>
</html>

Variables and Data Types

A variable is a named container for a value, and JavaScript has three ways to declare one. var has function scope and can be redeclared. let has block scope and cannot be redeclared in the same scope. const also has block scope, cannot be redeclared, and additionally cannot be reassigned once given a value, so a const must be initialized at the point it is declared.

var x = 5;
let y = 6;
const PI = 3.14159;
// PI = 3.14; would throw a TypeError, since PI cannot be reassigned

JavaScript's core data types are Number (both integers and floating-point values, plus the special values Infinity and NaN), BigInt (for integers beyond the safe range of Number, roughly $\pm(2^{53}-1)$), String (text inside single quotes, double quotes, or backticks), Boolean (true or false), and the special value undefined, given automatically to a variable that has been declared but not assigned.

Statements: Expression, Keyword, Block

A JavaScript program is a sequence of statements, instructions the engine executes in order, built out of values, operators, expressions, keywords and comments. An expression is any piece of code that evaluates to a value, arithmetic (10 + 3), string ("hello" + "world"), or logical (a === b), and expressions can appear anywhere a value is expected, such as a function argument. Keywords (let, return, if, else, for, switch, and dozens more) are reserved words that cannot be used as variable or function names. A block groups zero or more statements inside curly braces, { ... }, most often the body of a function, loop or conditional.

Operators

JavaScript's assignment operator (=) stores a value in a variable. The arithmetic operators are addition (+), subtraction (-), multiplication (*), division (/), modulus (%), increment (++) and decrement (--). Comparison operators include == (loose equality, converts types before comparing), === (strict equality, compares value and type together), !=, !==, <, >, <= and >=. Logical operators are && (and), || (or) and ! (not).

let x = 5, y = 2;
let z = x + y;        // 7
let equalStrict = (x === 7);   // true, same value and type

Flow Controls

Flow control decides which blocks of code run and in which order. The if...else statement runs one block when a condition is true and another when it is false; else if chains test additional conditions in sequence.

if (age > 18) {
  citizen = "voter";
} else if (age > 0) {
  citizen = "non-voter";
} else {
  citizen = "invalid age";
}

The switch statement chooses one of several code blocks to run based on an expression's value, falling through to the next case unless a break stops it, with an optional default block for no match.

switch (new Date().getDay()) {
  case 0:
    day = "Sunday";
    break;
  case 1:
    day = "Monday";
    break;
  default:
    day = "Another day";
}

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

SelectorDescriptionExample
Element SelectorSelects elements based on element name$("p") selects all <p> elements
ID SelectorSelects a single element with a specific id$("#myId")
Class SelectorSelects all elements with a specific class$(".myClass")
Universal SelectorSelects all elements$("*")
this SelectorRefers 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 milliseconds
  • callback - 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:

  1. css("color", "red") - changes the text color of #div to red
  2. .slideUp(200) - slides the element up in 200 milliseconds
  3. .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

FeatureDescriptionKey Benefit
SelectorsFind/select HTML elements by name, id, classEasy DOM access
CallbackFunction executed after an effect finishesEnsures sequential execution
ChainingMultiple methods applied to same element in one lineShorter, cleaner code

Note: jQuery follows the syntax $(selector).action() where $ grants access to jQuery, selector finds HTML elements, and action() performs operations on them.

Open this answer on its own page →

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]

The jQuery id selector uses the id attribute of an HTML tag to find and select a specific element. Since the id of an element is unique within a page, the id selector is used to select one unique element. Syntax: - The (hash) character is written followed by the id of the HTML element. -

Open this answer on its own page →

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]

  • Prompt box is used to fetch/take value from the user. - Syntax: prompt("message", "default value"); - Alert box is used to display a message to the browser. - Syntax: alert("message"); The task is to combine both: take input using prompt() and display that input using alert(). --- --- Step Desc...
Open this answer on its own page →

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 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:

FlagDescription
iCase-insensitive matching
gGlobal match (find all matches)
mMultiline matching

Common Methods:

MethodDescription
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

PatternMeaning
^[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.

Open this answer on its own page →

2080 · 5 marks

How HTML elements are accessed using getElementById and getElementByTagName, illustrate using HTML script. [5]

JavaScript provides built-in DOM (Document Object Model) methods to access and manipulate HTML elements: Method Description ------ getElementById("id") Accesses a single element by its unique id attribute getElementsByTagName("tag") Accesses a collection of elements by their HTML tag name --- - S...

Open this answer on its own page →

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]

--- - The <form tag uses the onsubmit event handler to call validateForm(). - Returning false from the function prevents form submission if validation fails. - Checks that the textbox is not empty (required field). - The default option has value="", so if nothing is selected, validation fails. - ...

Open this answer on its own page →

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]

Create an HTML form with: - Username: required, minimum length 4 - Password: required, must start with a character (a-z/A-Z) and end with - Country: must be selected (dropdown) - Gender: must be selected (radio button) --- --- Field Validation Rule ----------------------- Username Required; lengt...

Open this answer on its own page →

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

ElementTypePurpose
<input type="text">Text boxAccepts username input
<input type="password">Password fieldAccepts password (masked)
<input type="checkbox">CheckboxAllows hobby selection
onsubmit="return validate()"Event handlerCalls validation before submit

Note: The onsubmit event handler calls the validate() function. If the function returns false, 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 false to 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)
Open this answer on its own page →

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]

--- - The <form tag's onsubmit="return validateForm()" calls validateForm() every time the user clicks Sign Up. If validateForm() returns false, the browser cancels the submission and the error messages stay visible next to each field. - Each field has its own dedicated validation function (valid...

Open this answer on its own page →

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]

As per the notes, an array is a special variable which can hold more than one value at a time. We can access the values of an array by referring to an index number, and the index of an array starts with 0. Arrays are special types of objects in JavaScript. Syntax: --- Below is the complete HTML a...

Open this answer on its own page →

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

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

Open this answer on its own page →

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]

The jQuery animate() method is used to create custom animations on HTML elements by gradually changing CSS properties from one value to another. Syntax: Parameters: - {parameters} - Specifies the CSS properties to be animated (required) - speed - Optional. Specifies the duration: "slow", "fast", ...

Open this answer on its own page →

2076 · 5 marks

How jQuery animate can be used to create custom animation? Write syntax with sample script. [5]

With jQuery, the animate() method is used to create custom animations by gradually changing CSS properties of an element over a specified duration. It allows developers to animate numeric CSS properties such as width, height, opacity, left, top, margin, padding, etc. --- Parameter Description ---...

Open this answer on its own page →

Introduction to JSON

2078 · 5 marks

Discuss about different JSON data types. [5]

JSON (JavaScript Object Notation) supports the following six data types for values: --- A string is a sequence of characters written in double quotes. --- A number can be an integer or a floating-point value. It is written without quotes. --- A JSON object is a collection of key-value pairs enclo...

Open this answer on its own page →

2076 · 5 marks

What is the use of JSON? How can you parse a JSON, illustrate with an example. [5]

JSON (JavaScript Object Notation) is a lightweight, text-based data interchange format used to store and exchange data between a server and a web application. - Used to exchange data between a client and a server in web applications. - Used to store structured data in a simple, readable format. -...

Open this answer on its own page →

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]

An object in JavaScript is a collection of key-value pairs (properties and methods).: "Objects are similar to variables but objects can contain many value of different types. The values are written as name:value pairs." --- The simplest and most common method. Properties are defined directly insi...

Open this answer on its own page →