0% found this document useful (0 votes)
15 views22 pages

Lesson 11 (E)

ghrhrh yhrhr r rthr thr r rthrthrthr

Uploaded by

DK White Lion
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
15 views22 pages

Lesson 11 (E)

ghrhrh yhrhr r rthr thr r rthrthrthr

Uploaded by

DK White Lion
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 22

11 User Interaction and Time Controls

Lesson Introduction
In previous lessons you have learnt about html forms, JavaScript Programing
Concepts and JavaScript functions. So, in this section, you will gain knowledge about
how to pass form data into JavaScript functions and create instant messages. Also,
you will gain knowledge about jQuery, which is JavaScript function library. They are
introduction of jQuery, use of jQuery and jQuery form validation. Further, you will
learn about time control and event handling in this week.

Learning Outcomes:
After completion of this lesson, you will be able will be able to create interactive web
forms and validate inputs including input output programming.

This lesson enables you to


• Create web forms to access data from JavaScripts
• Access form data and create instant messages
• Create dynamic web elements with time control functions
• Validate form inputs with JQuery library

Lesson Outline
• Passing form data into JavaScripts
• Form events and event handling
• Time control functions
• Introduction to JQuery library
• Use of JQuery Library
11.1 Passing form data into JavaScript
In previous lessons you have learnt about html forms, JavaScript functions. So, in this
lesson, we will discuss how to pass form data into JavaScript functions. An example
simple HTML form is shown below.

<!DOCTYPE html>

<html>
<body>
<h2>My Form</h2>

<form>

First name:<input type="text" name="firstname" value=""><br>


Last name:<input type="text" name="lastname" value="">

<br><br>

<input type="button" name="button" value="Click">


</form>
</body>

</html>

In this example, we are going to pass this form data to a JavaScript function. In above
example, data include firstname and lastname. To pass these data to a JavaScript
function, we need to create references. So, we need to provide a name and id for the
form itself for use with JavaScript. Following statement shows the form name and id.

<form name="myform" id="myformId"


>
Also, we need to add an event handler to trigger the form event. Event handlers can be
onClick, onSubmit etc. These are handling an event. Example statement of an onClick
event handler is shown below.

<input type="button" name="button" value="Click" onClick="result()">

onClick event handler is used to click a button. When the button is clicked, JavaScript
executes the expression within the quotes. The expression says to call the result()
function elsewhere on the page and pass it to the current form object. Following
example <script> code shows the passing of firstname and lastname text field values to
the result() function of JavaScript when button is clicked. Then the text box values are
taken using “document.getElementById("firstname").value” to variables. Then full name
is displayed from variables on the label.

<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">

function result(){

var fname = document.getElementById("firstname").value;


var lname = document.getElementById("lastname").value;
document.getElementById("res").innerHTML = "Hello "+fname+" "+lname;

}
</script>
</head>

<body>

<h2>My Form</h2>

<form name="myform" id="myformId">


First name:<input type="text" id="firstname" value=""><br>

Last name:<input type="text" id="lastname" value="">

<br><br>
<input type="button" name="button" value="Click" onClick="result()"><br><br>

<label id="res"></label>
</form>

</body>
</html>

Activity 11.1: Write above web script and observe the output with form event. Then
understand the behavior of form event functions.
Here we will discuss, how to access form data and create instant message in an alert box.
We can pass parameters to JavaScript functions. According to the following example,
when the button is clicked in the form, resultant function is passed the form object as
the parameter using this.form (the this keyword references to the button control; form
is a property of the button control and represents the form object).
When the data is pass to the JavaScript function using form object, we can get textbox
values using “form.inputbox.value” to a variable. Then we can display that variable value
in an alert box.
<html>
<head>

<script type="text/javascript">
function result(form) {

var TestVar = form.inputbox.value;


alert ("You typed: " + TestVar);

</script>
</head>

<body>

<form name="myform" >Enter something in the box: <br>


<input type="text" name="inputbox" value=""><p>
<input type="button" name="button" value="Click" onClick="result(this.form)">

</form>

</body>
</html>

Above example shows the way to obtain values from form objects. Load the page, then
type something into the text box. Click the button, and what you typed is shown in the
alert box.

Activity 11.2: Write above web script and observe the output with form event. Then
understand the behavior of form event functions.
11.2 Form events and event handling
Events allow us to trigger JavaScript code that reacts to certain situations. Example of
events is the user clicking the mouse, the web page loading and a form field being
changed, etc.
JavaScript provides event handlers to run bits of code when these events occur. All the
event handlers in JavaScript start with “on” and each event handler deals with a certain
type of event. Table 11.1 shows some event handlers and their descriptions. There are
certain JavaScript event handlers for form events, which are shown in Table 11.2.

Table 11.1. Some event handlers and their descriptions


Event Handlers Description

onBlur The event occurs when an element loses focus.


onChange The event occurs when the content of a form element, the
selection or the checked state have changed
onClick The event occurs when the user clicks on an element.
onError The event occurs when an error occurred during the loading of a
media file.
onFocus The event occurs when an element get focus.
onKeyPress The event occurs when the user presses a key.
onLoad The event occurs when the whole page has finished loading.
onMove The event occurs when the user moves the browser window or
frame.
onSubmit The event occurs when the user clicks the form’s Submit button.

Table 11.2. Some Form events and their descriptions

Event Description
Handlers
onBlur The event occurs when an element loses focus.
onChange The event occurs when the content of a form element, the selection
or the checked state have changed
onFocus The event occurs when an element gets focus.
onFocusin The event occurs when an element is about to get focus.
onFocusout The event occurs when an element is about to lose focus.
onInput The event occurs when an element gets user inputs.
onInvalid The event occurs when an element is invalid.
onReset The event occurs when a form is reset.
onSearch The event occurs when the user writes something in a search field.
onSelect The event occurs after the user selects some text.
onSubmit The user clicks the form’s Submit button.

References: https://www.elated.com/articles/events-and-event-handlers/
https://www.w3schools.com/jsref/dom_obj_event.asp

11.3 Time control functions


The window object allows execution of code at specified time intervals when it is ask to
execute. These time intervals are called timing events. There are two key time control
functions to use with JavaScript. Such as

1. setTimeout(function, milliseconds)
Execute a function, after waiting a specified number of milliseconds.

2. setInterval(function, milliseconds)
Same as the setTimeout(), but repeats the execution of function
continuously.

11.3.1 The setTimeout() function

window.setTimeout(function, milliseconds)
window.setTimeout() function can be written without the window prefix. First
parameter is a JavaScript function to be executed. Second parameter indicates the
number of milliseconds before execution.

In the following code example, it executes when click the button, wait 3 seconds and the
page will alert “Hello”.

!DOCTYPE html>
<html>
<body>
<p>Click "Try it". Wait 3 seconds, and the page will alert "Hello".</p>
<button onClick="setTimeout(myFunction, 3000);">Try it</button>
<script>
function myFunction() {
alert('Hello');
}
</script>
</body>
</html>

Activity 11.3: Write above web script and observe the output with button click event. Then
understand the time control function setTimeout().

To stop the execution of function specified in setTimeout(). window.clearTimeout()


function can be written without the window prefix. The clearTimeout() function uses the
variable returned from setTimeout().

myVar = setTimeout(function, milliseconds);


clearTimeout(myVar);

If the function has not already been executed, we can stop the execution by calling the
clearTimeout() function.
The following example uses both setTimeout() and clearTimeout() functions to execute
and stop.

<!DOCTYPE html>
<html>
<body>
<p>Click "Try it". Wait 3 seconds. The page will alert "Hello".</p>
<p>Click "Stop" to prevent the first function to execute.</p>
<p>(You must click "Stop" before the 3 seconds are up.)</p>

<button onclick="myVar = setTimeout(myFunction, 3000)">Try it</button>


<button onclick="clearTimeout(myVar)">Stop it</button>

<script>
function myFunction() {
alert("Hello");
}
</script>
</body>
</html>

Activity 11.4: Write above web script and observe the output with button click event. Then
understand the time control function clearTimeout().

11.3.2 The setInterval() function


The setInterval() method repeats a given function at every given time-interval.

window.setInterval(function, milliseconds);

window.setInterval() function can be written without the window prefix. First


parameter is a JavaScript function to be executed. Second parameter indicates the
length of time-interval between each execution. Following example shows the execution
of a function called “myTimer” once every second.
Example: Display the current time.

<!DOCTYPE html>
<html>
<body>
<p>A script on this page starts this clock:</p>
<p id="demo"></p>
<script>
var myVar = setInterval(myTimer, 1000);
function myTimer() {
var d = new Date();
document.getElementById("demo").innerHTML = d.toLocaleTimeString();
}
</script>
</body>
</html>

Activity 11.4: Write above web script and observe the output with time control event. Then
understand the time control function setInterval().

To stop the execution of function specified in setInterval(). window.clearTimeout()


function can be written without the window prefix. The clearTimeout() function uses the
variable returned from setInterval().

myVar = setInterval(function, milliseconds);


clearTimeout(myVar);

The setInterval() function can be used to change the web content dynamically and
periodically. This is a very good event to change the appearance of web pages.

The following example shows with an added “Stop Time” button.


<!DOCTYPE html>
<html>
<body>
<p>A script on this page starts this clock:</p>
<p id="demo"></p>
<button onclick="clearInterval(myVar)">Stop Time</button>
<script>
var myVar = setInterval(myTimer ,1000);
function myTimer() {
var d = new Date();
document.getElementById("demo").innerHTML = d.toLocaleTimeString();
}
</script>
</body>
</html>

Activity 11.5
Create following HTML form with JavaScript to display employee name and net
salary. Upload your web script to the given link in the moodle.

Note: Net Salary = (Working Hours*250) – (Working Hours*250*0.08)


11.4 Introduction to JQuery library
jQuery is JavaScript Library(Framework). It simplified usage of JavaScript. It has a bunch
of inbuilt functionalities on call. Some of those functionalities are:
1. Access parts of a page
• Some cases using CSS
2. Modify the appearance of a page
3. Alter the content of a page
4. Change the user’s interaction with a page
5. Add animation to a page
6. Provide AJAX support

It is a lightweight “write less, do more” JavaScript library. The purpose of jQuery is to


make it easier to use JavaScript on our web site. jQuery takes a lot of common tasks that
require many lines of JavaScript code to accomplish and wraps them into functions that
we can call with a single line of code, where it enhances the reusability of code.

jQuery library contains following features:


1. HTML element selections
2. HTML element manipulation
3. CSS manipulation and HTML event functions
4. JavaScript effects and animations
5. HTML DOM traversal and modification
6. AJAX
7. Utilities

11.5 Use of Jquery Library


There are two ways to start using jQuery on our web site. They are
Ø Download the jQuery library from jQuery.com
Ø Include jQery from Content Delivery Network (CDN), like Google
Downloading jQuery
There are two versions of jQuery available for downloading.

1. Production version
It is for live web sites because it has been minified compressed.

2. Development version
This is for testing and development. It has been uncompressed and readable
code.

Both versions can be downloaded from - http://jquery.com


The jQuery library is single JavaScript file. It is linked with <script> tag inside the <head>
section of HTML code. Example is given below.

<head>
<script src="jquery-3.3.1.min.js" ></script>
</head>

The downloaded jQuery library file should be placed inside the same directory of other
html files, otherwise the page cannot load the library.

jQuery CDN
We can use the CDN to reference jQuery library, instead of downloading it. You can find
the latest version of jQuery in Google's or Microsoft’s Hosted Libraries. To load a hosted
library, copy and paste the HTML snippet for that library from the official website in your
web page.
Google CDN is shown in the following code snippet (versions can be changed time to
time):

<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
</script>
</head>
Microsoft CDN is shown in the following example:

<head>
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.3.1.min.js">
</script>
</head>

By comparing a simple "Hello World!" program in both JavaScript and jQuery, we can see
how jQuery differ from JavaScript.

JavaScript Program:

<html>
<body>
<p id="Test"></p>
<script type="text/javascript">
document.getElementById("Test").innerHTML = "Hello World!";
</script>
</body>
</html>

jQuery Program:

<html>
<head>
<script type="text/javascript" src="jquery-3.3.1.js"></script>
</head>
<body>
<p id="Test"></p>
<script type="text/javascript">
$("#Test").text("Hello World!");
</script>
</body>
</html>
Activity 11.6: Try the above JQuery example after downloading the jQuery library. Then
understand the ease of use of jQuery.

11.5.1 jQuery Syntax

The jQuery syntax is tailor-made for selecting HTML elements and performing
some action on the element(s).
Basic syntax is: $(selector).action()
Ø A $ sign to define/access jQuery
Ø A (selector) to "query (or find)" HTML elements
Ø A jQuery action() to be performed on the element(s)

Examples:
$(this).hide() - hides the current element.
$("p").hide() - hides all <p> elements (paragraphs).
$(".test").hide() - hides all elements with class="test".
$("p.test").hide() – hides all <p> elements (paragraph) with class="test".
$("#test").hide() - hides the element with id="test".

Selecting part of a document is fundamental operation. A jQuery object is a wrapper for


a selected group of DOM (Document Object Model) nodes. $() function is a factory
method that creates jQuery objects. $(“XX”) is a jQuery object containing all the “XX”
elements in the document.

.addClass() method changes the DOM nodes by adding a ‘class’ attribute. The ‘class’
attribute is a special CSS construct that provides a visual architecture independent of the
element structures.

$(“dt”).addClass(“emphasize”) will change all occurrences of <dt> to


<dt class=“emphasize”>
To make this change, it is put in a function.
function doEmph()
{$(“dt”).addClass(“emphasize”)}

It is called when the document has been loaded and the DOM is created.
<body onLoad=“doEmph()”>
<dt class=“emphasize”></dt>
</body>

Structure and appearance should be separated. Also, onLoad waits until all images etc.
are loaded.

jQuery provides an independent scheduling point after DOM is created and before images
are loaded.
$(document).ready(doEmph);

HTML modifications are not required. All modifications are done in script. Following
example is given a better solution for document ready event.

$(document).ready(function(){
$(“dt”).addClass(“emphasize”)
});

The following example can be used to observe the functionality and embedded power of
jQuery functions where it saves large number of code writing time.
Example 1: Hide the text, when user clicks it.

<html>
<head>
<script type="text/javascript" src="jquery-3.3.1.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("p").click(function(){
$(this).hide();
});});
</script>
</head>
<body>
<p>click on me to hide me.</p>
</body>
</html>

Example 2: All <p> elements will be hidden, when user clicks the button.
<html>
<html>
<head>
<script src="jquery-3.3.1.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("p").hide();
}); });
</script>
</head>
<body>
<h2>This is a heading</h2>
<p>This is a paragraph.</p>
<p>This is another paragraph.</p>
<button>Click me to hide paragraphs</button>
</body>
</html>
Example 3: Hide the button, when user clicks the button.
<html>
<head>
<script type="text/javascript" src="jquery-3.3.1.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("button").click(function(){
$(this).hide();
}); });
</script>
</head>
<body>
<button>Click me</button>
</body>
</html>

Example 4: An element with id= "test" will be hidden, when user clicks the button.
<!DOCTYPE html>
<html>
<head>
<script src="jquery-3.3.1.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("#test").hide();
}); });
</script>
</head>
<body>
<h2>This is a heading</h2>
<p>This is a paragraph.</p>
<p id="test">This is another paragraph.</p>
<button>Click me</button>
</body>
</html>
Example 5: An element with class= "test" will be hidden, when user clicks the button.
<html>
<head>
<script type="text/javascript" src="jquery-3.3.1.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("button").click(function(){
$(".test").hide();
}); });
</script>
</head>
<body>
<h2 class="test">This is a heading</h2>
<p class="test">This is a paragraph.</p>
<p>This is another paragraph.</p>
<button>Click me</button>
</body>
</html>

Activity 11.7: Try the above JQuery examples 1-5 and understand the variety of functional
execution models in use of jQuery.

1.5.2 jQuery Selectors

jQuery selectors allow us to select and manipulate HTML elements as a group or as a


single element.

jQuery selectors are required at every step while using jQuery. Selectors allow you to get
the exact element/attribute you want from your HTML document. jQuery supports the
existing CSS Selectors, and in addition, it has some own custom selectors.

All type of selectors in jQuery, start with the dollar sign and parentheses: $(). Table 11.3
shows some examples of jQuery Selectors.
Table 11.3. Some examples of jQuery Selectors

Syntax Description

$("*") Selects all elements.


$("p") Selects all <p> elements.
$("p.intro") Selects all <p> elements with class="intro".
$("p#intro") Selects all <p> elements with id="intro".
$("p:first") Selects the first <p> element.
$(":animated") Selects all elements that are currently animated.
$("[href]") Selects all elements with a href attribute
$(":button") Selects all <button> elements and <input> elements of
type="button".
$(":even") Selects even elements.
$(":odd") Selects odd elements.

Example 6: Here the text will be hidden, when user clicks the “Hide” button. Then text
will be displayed, when user clicks the “Show” button.

<html> <head>
<script type="text/javascript" src="jquery-3.3.1.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#hide").click(function(){
$("p").hide(); });
$("#show").click(function(){
$("p").show(); });
});
</script>
</head>
<body>
<p>If you click on the "Hide" button, I will disappear.</p>
<button id="hide">Hide</button>
<button id="show">Show</button>
</body>
</html>
Activity 11.8: Try the above JQuery examples 6 and understand how event listeners are
operating in JavaScript functional execution models in use of jQuery.

11.5.3 jQuery Form Validation


JQuery libraries are extensively used in form feed data validation and input validations
which helps programmer to detect incompleteness of input data before sending it to the
server.

The above HTML form validation code is given below.

Activity 11.9: Create the above HTML form and link the following JQuery script for the input
validation. You have to be creative and investigative to use the following script. Please upload
your final code into the given link of Moodle.
// Wait for the DOM to be ready
$(function() {
// Initialize form validation on the registration form. It has the name attribute "registration"
$("form[name='registration']").validate({
// Specify validation rules
rules: {
// The key name on the left side is the name attribute of an input field. Validation rules are
// defined on the right side
firstname: "required",
lastname: "required",
email: { required: true,
// Specify that email should be validated by the built-in "email" rule
email: true },
password: {
required: true,
minlength: 5
} },
// Specify validation error messages
messages: {
firstname: "Please enter your firstname",
lastname: "Please enter your lastname",
password: {
required: "Please provide a password",
minlength: "Your password must be at least 5 characters long"
},
email: "Please enter a valid email address"
},
// Make sure the form is submitted to the destination defined
// in the "action" attribute of the form when valid
submitHandler: function(form) {
form.submit();
} }); });

Reference: https://www.sitepoint.com/basic-jquery-form-validation-tutorial/
Activity 11.10
Create an html page to display the following table with jQuery script to hide
all even table rows. Upload your final web script in to the moodle.

Summary
Now you have completed learning lesson 11. We have discussed about Passing form
data into JavaScripts, Form events and event handling, Time control functions,
JQuery library and Use of JQuery Library.

You might also like