You are on page 1of 11

Chapter 3 – Forms and Events

3.1 Introduction
The interesting behaviour of a system tends to be dependent on changes to the state of the system as
a whole, or to its components. The kind of interaction a Web application might include usually
involves short-term changes of state in which it is only important to know that they have occurred.
That is the change of state is not intended to persist; it happens and it is not stored explicitly in the
system. Such a change is indicated by an event.
In the context of JavaScript, an event is an action that occurs in a browser that
JavaScript provides facilities to detect and so act upon. Events are generally related to user
interactions with the document, such as clicking and pointing the mouse, although some are
related to changes occurring in the document itself. Programming JavaScript to handle such events
provides for many styles of human-computer interaction. In short, programming JavaScript event
handlers is crucial if you want interactive Web pages. When this style of programming dominates your
design, it is known as event-based programming
Form:-
The form property within the document object contains an array of all forms defined within the
document.
Each element within the array is a form object , the index number associated with the form object
defines the order in which the form appears on the webpage.
Table : Event handlers for Form Elements.
Object Event Handler
Button onClick, onBlur, onFocus
Checkbox onClick, onBlur, onFocus.
FileUpLoad onClick, onBlur, onFocus
Hidden None
Password onBlur, onFocus, onSelect.
Radio onClick, onBlur, onFocus
Reset onReset.
Select onFocus, onBlur, onChange.
Submit onSubmit
Text onClick, onBlur, onFocus , onChange
Textarea onClick, onBlur, onFocus , onChange

JavaScript Form Events : Buttons


The main utility of a button object is to trigger an event, say an onClick() event, but a button object
has no default action.
The are several types of buttons associated with a form:
 submit
 reset
 button
Syntax:-
<button type="button">Click Me!</button>
<input type=”button”>
The <button> tag defines a clickable button.
Inside a <button> element you can put content, like text or images. This is the difference between this
element and buttons created with the <input> element.
Tip: Always specify the type attribute for a <button> element. Different browsers use different
default types for the <button> element
Program:-
<button name="button" value="OK" type="button" onclick="hello()">Click Here
</button>
<script>
function hello()
{
alert("hello javatpoint user");
}
</script>

Textarea Properties:-
The textContent property sets or returns the text content of the specified node, and all its
descendants.
If you set the textContent property, any child nodes are removed and replaced by a single Text node
containing the specified string.
Note: This property is similar to the innerText property, however there are some differences:
 textContent returns the text content of all elements, while innerText returns the content of all
elements, except for <script> and <style> elements.
 innerText will not return the text of elements that are hidden with CSS (textContent will). Try
it »
Tip: Sometimes this property can be used instead of the nodeValue property, but remember that this
property returns the text of all child nodes as well.
var x = document.getElementById("myBtn").textContent;

Properties:-

Property Description

autofocus Sets or returns whether a text area should automatically get focus
when the page loads

cols Sets or returns the value of the cols attribute of a text area

defaultValue Sets or returns the default value of a text area

disabled Sets or returns whether the text area is disabled, or not

form Returns a reference to the form that contains the text area

maxLength Sets or returns the value of the maxlength attribute of a text area

name Sets or returns the value of the name attribute of a text area

placeholder Sets or returns the value of the placeholder attribute of a text area
readOnly Sets or returns whether the contents of a text area is read-only

required Sets or returns whether the text area must be filled out before
submitting a form

rows Sets or returns the value of the rows attribute of a text area

type Returns the type of the form element the text area is

value Sets or returns the contents of a text area

wrap Sets or returns the value of the wrap attribute of a text area

Mouse Event:-
These events are fired when some click related activity is registered.
The mouse events are by far the most important events. On this page I introduce some of
the most common problems and tricks. We'll go through all mouse events: mousedown, mouseup and
click, dblclick, mousemove and finally mouseover and mouseout.
Table : The MouseEvent Object.
Event Handler Triggered When

onBlur The form's select, text, or textarea field loses focus.

A select , text ot textarea field has lost the focus and values
onChange
are changed.

onClick An object on a form gets clicked.

onFocus a field gets input focus.

onReset The the form is reset

onSelect text within the textarea field is selected

onSubmit A form is submitted

Program:-
<html>
<body>
<h2 onclick="showCoords(event)">Click this heading to get the x (horizontal) and y (vertical)
coordinates of the mouse pointer when it was clicked.</h2>
<p><strong>Tip:</strong> Try to click different places in the heading.</p>
<p id="demo"></p>
<script>
function showCoords(event) {
var x = event.clientX;
var y = event.clientY;
var coords = "X coords: " + x + ", Y coords: " + y;
document.getElementById("demo").innerHTML = coords;
}
</script> </body>
</html>

Checkbox:-
The checked attribute is a boolean attribute.
When present, it specifies that an <input> element should be pre-selected (checked) when the
page loads.
The checked attribute can be used with <input type="checkbox"> and <input type="radio">.
The checked attribute can also be set after the page load, with a JavaScript.
Program:-
<!DOCTYPE html>
<html>
<body>
<h1>Show checkboxes:</h1>
<form action="/action_page.php">
<input type="checkbox" name="vehicle1" value="Bike"> I have a bike<br>
<input type="checkbox" name="vehicle2" value="Car"> I have a car<br>
<input type="checkbox" name="vehicle3" value="Boat" checked> I have a boat<br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
Radio Button:-
o get the value of selected radio button, a user-defined function can be created that gets all the radio
buttons with the name attribute and finds the radio button selected using the checked property. The
checked property returns True if the radio button is selected and False otherwise. If there are multiple
Radio buttons in a webpage, first, all the input tags are fetched and then the values of all the tags that
have type as ‘radio’ and are selected are displayed.
Attributes:
Property Description
defaultChecked Returns the default value of the checked attribute
defaultValue Sets or returns the default value of a radio button
Disabled Sets or returns whether the radio button is disabled, or not
Form Returns a reference to the form that contains the radio button

Program:-
<head>
<title>
Get value of selected
radio button
</title>
</head>

<body>
<p>
Select a radio button and click on Submit.
</p>

Gender:
<input type="radio" name="gender" value="Male">Male
<input type="radio" name="gender" value="Female">Female
<input type="radio" name="gender" value="Others">Others

<br>

<button type="button" onclick="displayRadioValue()">


Submit
</button>

<br>
<div id="result"></div>
<script>

function displayRadioValue() {
var ele = document.getElementsByName('gender');

for(i = 0; i < ele.length; i++) {


if(ele[i].checked)
document.getElementById("result").innerHTML= "Gender: "+ele[i].value;
}
}
</script>
</body>
</html>
Form Events:-

ttribute Value Description

onblur script Fires the moment that the element loses focus

onchange script Fires the moment when the value of the element is changed

oncontextmenu script Script to be run when a context menu is triggered

onfocus script Fires the moment when the element gets focus

oninput script Script to be run when an element gets user input


oninvalid script Script to be run when an element is invalid

onreset script Fires when the Reset button in a form is clicked

onsearch script Fires when the user writes something in a search field (for
<input="search">)

onselect script Fires after some text has been selected in an element

onsubmit script Fires when a form is submitted

Program:-
<!DOCTYPE html>
<html>
<head><title>Javascript Form Events : keyword this</title>
<script>
function validateF(iform){
alert("Value within Text Field is :" +
iform.namestring.value );
}
</script>
</head>
<body>
<hr>
<form name ="demo_form">
<p>
Name :
<input type="text" name="namestring" size="50" />
</p>
<input type="button"
value="print fromfield contents"
onclick="validateF(this.form);" /> <!-- Reference to the form object
using this keyword ---->
<input type="reset" value="clear all">
</form> </body> </html>
onClick:
We have already used this event in our programming area. Now we can use it with buttons, images,
links, radio buttons, and check boxes. Now a simple onClick event used with an image:
Listing 1: Showing onClick event
<img class='imagem_artigo' SRC = cei.jpg onClick = "alert(Welcome to Computer Educational
Institution.')">

onDblClick:
onDblClick is also the same process like onClick event. Using this event we can easily measure the
status through the following code: In the following code we can access the data by just double
clicking on the button.
Listing 2: Showing onDblClick event
<img class='imagem_artigo' SRC = cei.jpg onDblClick = "alert(Welcome to Computer Educational
Institution.')">

onKeyDown:
This event fires when a key on our keyboard is pressed down. It can apply to the buttons, textboxes,
text areas, and links. If we had a search box on the form, for example, if I want to activate the search
when the user presses then it will be Return/Enter key on the keyboard. But who are using Netscape
Navigator Browser they use this code:
Listing 3: Showing onKeyDown event

window.captureEvents(Event.KEYPRESS)

But it is a problem stating process so we always capture the easier example of the KeyDown event
that works in both browsers is this way:
<INPUT type = text onKeyDown = "alert('Key pressed Welcome to Computer Educational Centre')">

onMouseOver:
This is also very nice event. This action is already done when we wrote the script for the
"twirling hand". Associated events are onMouseOut and onMouseDown. They are generally used for
links and images. Generally it is used when onMouseOver is used to swap images around for creating
a rollover effect.

Onblur:
Basically this event precedes a place when objects lose focus (change the cursor position). If
we click inside the text box then click outside it and the textbox has lost focus. That movement
onBlur event will be fired. The following code easily demonstrates the working principal of the
onblur event.
Listing 4: Showing onKeyDown event
<INPUT TYPE = text onBlur = "alert ('Lost focus from here……..')">

onSubmit:
This is a very useful event that can be used for data validation on a form. Sending data from
one page to another page it is takes a vital role. We can use this event with a Submit button. The
details on the form can be checked for errors. We catch any error and we can stop the form's details
from being submitted.
Note the use of the word return statement. This is set to a Boolean value. If we return it false,
which means wrong arguments then the form cannot be submitted. On the other hand if it is true then
the form is submitted successfully.
Listing 5: Showing onsubmit event and validation
<form name = form1 onsubmit = "return validate1()">
<input type = submit value = " send ">
</form>
This form is not very secure because it is only Submit button. But if we set this submit button
through the following manner then it checks data step by step.
function Validate()
{
flag = false
if (flag == false)
{
alert("An Errors detected……..");
return false
}
if (flag == true)
{
alert("Form Submitted Successfully…..");
return true
}

}
In this function we can set a variable (flag) to false. This is just used for testing purpose
and that means the user has filled up the form incorrectly. We look at the two return values though. If
the Details are false then return is set to false message from the user and the form doesn’t get
submitted. Other hand when the details are true then return is true and the form is submitted
successfully.
Then the procedure is like this:
<form name = f1 onSubmit = "return validate()"
Method = post Action="ceimaa.netii.net" Enctype="text/plain">

Real life example of Javascript Even:


This all are the simple examples of the Javascript event handling in our dynamic website
buildup procedure. But this is not enough for us in developing Javascript. So now, we have to look at
the real time example.
This is example is given below to execute Javascript function and also work efficiently.
Listing 6: Showing form validation
<html>
<head>
<script>
function validate_form() // This is function definition part
{

var a=document.forms["mypage"]["fname"].value;
if (a==null || a=="")
{
alert("First name must be filled out");
return false;
}}
</script>
</head>
<body>
<form name="mypage" action="cei_form.jsp" onsubmit="return validate_form()" method="post">
Enter First name: <input type="text" name="fname">
Enter Last name: <input type="text" name="lname">
<input type="submit" value="Submit">
</form> </body> </html>
When we use the following code and give no arguments in the text box then this type of alert
message will be displayed.

Figure 1: Showing alert message


Listing 7: Sample showing back ground color change
<html>
<head>
<title>
</title>
</head>
<script type="text/javascript">
function cchange(bgval)
{
nc = bgval.options[bgval.selectedindex].text;
document.bgcolor = nc;
bgval.selectedindex = -1;
}
</script>
<body style="font-family:tahoma;font-size:10pt;">
<div style="border:2px solid #fff; width:300px;text-align:center;">
<b>Processing to changing background colors…</b> <br>

<form style="padding:20px;">
<select size="8" onchange="bgchange(this);">
<option>red</option>
<option>orange</option>
<option>yellow</option> //This is option button that display as list box.
<option>green</option>
<option>blue</option>
<option>indigo</option>
<option>violet</option>
<option>white</option>
</select>
</form>
</body>
</html>

Form Object:-
The Form object represents an HTML <form> element.
Access a Form Object:-
You can access a <form> element by using getElementById():
Example:-
<!DOCTYPE html>
<html>
<body>
<h3>A demonstration of how to access a FORM element</h3>
<form id="myForm" action="/action_page.php">
First name: <input type="text" name="fname" value="Donald"><br>
Last name: <input type="text" name="lname" value="Duck"><br>
<input type="submit" value="Submit">
</form>
<p>Click the "Try it" button to get the URL for where to send the form data when the form above is
submitted.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction() {
var x = document.getElementById("myForm").action;
document.getElementById("demo").innerHTML = x;
}
</script>
</body>
</html>
Changing a Label Dynamically:-
There are many ways you can change the text of an element dynamically using
a small script at the client side. I am sharing two different examples here in this post
showing how to change the text of a label on button click using JavaScript
Program:-
Change Label Text on Button Click using JavaScript.
The first example is in JavaScript, where I am using two different properties to change the text of a
label. The properties are innerText and innerHTML. You can learn the difference between the two
properties here.
I said I have a button and a textbox on my web page. The button’s click event will call a function. In
that function I’ll get the value from the textbox and assign the value the label using the properties I
have mentioned above.
Using innerText-
<!DOCTYPE html>
<html>
<head>
<title>Using innerText</title>
</head>
<body>
Enter a Name: <input type="text" id="emp" value="" />
<p> <input type="button" id="bt" value="Change Label Text" onclick="changeLabel()" />
</p>

<label id="lblEmp">N/A</label>
</body>
<script>
function changeLabel() {
let lbl = document.getElementById('lblEmp');
let empName = document.getElementById('emp').value;

lbl.innerText = empName; // TREATS EVERY CONTENT AS TEXT.


}
</script>
</html>

Using innerHTML-

<!DOCTYPE html>
<html>
<head>
<title>Using innerHTML</title>
</head>

<body>
Enter a Name: <input type="text" id="emp" value="" />
<p>
<input type="button" id="bt" value="Change Label Text" onclick="changeLabel()" />
</p>
<label id="lblEmp">N/A</label>
</body>
<script>
function changeLabel() {
let lbl = document.getElementById('lblEmp');
let empName = document.getElementById('emp').value;

// Assign HTML codes along with text values using innerHTML.


lbl.innerHTML = 'Hello <span style="text-transform:capitalize;">' + empName + '</span>';
}
</script>
</html>

You might also like