Lesson 11 (E)
Lesson 11 (E)
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.
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>
<br><br>
</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.
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(){
}
</script>
</head>
<body>
<h2>My Form</h2>
<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) {
</script>
</head>
<body>
</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.
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
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.
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().
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>
<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().
window.setInterval(function, milliseconds);
<!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().
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.
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.
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.
<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.
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".
.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.
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.
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
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.
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.