Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
43 views

Java Script 8th Class

The document discusses forms in JavaScript. It explains that the <form> element is used to create a form in HTML and describes the action and method attributes. JavaScript uses the HTMLFormElement object to represent a form. Key properties and methods of this object include action, method, submit(), and reset(). The document also covers referencing forms, submitting forms, accessing form fields, and putting together a complete signup form with validation.

Uploaded by

RAVI Kumar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
43 views

Java Script 8th Class

The document discusses forms in JavaScript. It explains that the <form> element is used to create a form in HTML and describes the action and method attributes. JavaScript uses the HTMLFormElement object to represent a form. Key properties and methods of this object include action, method, submit(), and reset(). The document also covers referencing forms, submitting forms, accessing form fields, and putting together a complete signup form with validation.

Uploaded by

RAVI Kumar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 20

IT SPRING EDUTECH

A complete web solution

JavaScript Form
Form basics

To create a form in HTML, you use the <form> element:

<form action="/signup" method="post" id="signup">


</form>
Code language: HTML, XML (xml)

The <form> element has two important attributes: action and method.

 action specifies a URL that processes the form submission. In this example,
the action is the /signup URL.
 method specifies the HTTP method to submit the form with. The method is
either post or get.

Typically, you use the get method when you want to retrieve data from
the server and the post method when you want to change something on
the server.

JavaScript uses the HTMLFormElement object to represent a form.


The HTMLFormElement has the following properties that correspond to
the HTML attributes:

 action – is the URL that processes the form data. It is equivalent to


the action attribute of the <form> element.
 method – is the HTTP method which is equivalent to the method attribute of
the <form> element.

The HTMLFormElement element also provides the following useful


methods:

 submit() – submit the form.


 reset() – reset the form.

Referencing forms

To reference the <form> element, you can use DOM selecting methods
such as getElementById():

const form = document.getElementById('subscribe');


Code language: JavaScript (javascript)

An HTML document can have multiple forms.


The document.forms property returns a collection of forms
(HTMLFormControlsCollection) on the document:

document.forms
Code language: JavaScript (javascript)

To reference a form, you use an index. For example, the following


statement returns the first form of the HTML document:

document.forms[0]
Code language: CSS (css)

Submitting a form

Typically, a form has a submit button. When you click it, the browser
sends form data to the server. To create a submit button, you
use <input> or <button> element with the type submit:

<input type="submit" value="Subscribe">


Code language: HTML, XML (xml)

Or
<button type="submit">Subscribe</button>
Code language: HTML, XML (xml)

If the submit button has focus and you press the Enter key, the browser
also submits the form data.

When you submit the form, the submit event is fired before the request
is sent to the server. This gives you a chance to validate the form data.
If the form data is invalid, you can stop submitting the form.

To attach an event listener to the submit event, you use


the addEventListener() method of the form element as follows:

const form = document.getElementById('signup');

form.addEventListener('submit', (event) => {


// handle the form data
});
Code language: JavaScript (javascript)

To stop the form from being submitted, you call


the preventDefault() method of the event object inside the submit event
handler like this:

form.addEventListener('submit', (event) => {


// stop form submission
event.preventDefault();
});
Code language: PHP (php)

Typically, you call the event.preventDefault() method if the form data is


invalid.

To submit the form in JavaScript, you call the submit() method of the
form object:

form.submit();
Code language: CSS (css)
Note that the form.submit() does not fire the submit event. Therefore, you
should always validate the form before calling this method.

Accessing form fields

To access form fields, you can use DOM methods


like getElementsByName(), getElementById(), querySelector(), etc.

Also, you can use the elements property of the form object.
The form.elements property stores a collection of the form elements.

JavaScript allows you to access an element by index, id, or name.


Suppose that you have the following signup form with
two <input> elements:

<form action="signup.html" method="post" id="signup">


<h1>Sign Up</h1>
<div class="field">
<label for="name">Name:</label>
<input type="text" id="name" name="name"
placeholder="Enter your fullname" />
<small></small>
</div>
<div class="field">
<label for="email">Email:</label>
<input type="text" id="email" name="email"
placeholder="Enter your email address" />
<small></small>
</div>
<button type="submit">Subscribe</button>
</form>
Code language: HTML, XML (xml)

To access the elements of the form, you get the form element first:

const form = document.getElementById('signup');


Code language: JavaScript (javascript)
And use index, id, or name to access the element. The following
accesses the first form element:

form.elements[0]; // by index
form.elements['name']; // by name
form.elements['name']; // by id (name & id are the same
in this case)
Code language: JavaScript (javascript)

The following accesses the second input element:

form.elements[1]; // by index
form.elements['email']; // by name
form.elements['email']; // by id
Code language: JavaScript (javascript)

After accessing a form field, you can use the value property to access its
value, for example:

const form = document.getElementById('signup');


const name = form.elements['name'];
const email = form.elements['email'];

// getting the element's value


let fullName = name.value;
let emailAddress = email.value;
Code language: JavaScript (javascript)

Put it all together: signup form

The following illustrates the HTML document that has a signup


form. See the live demo here.

<!DOCTYPE html>
<html lang="en">
<head>
<title>JavaScript Form Demo</title>
<meta name="viewport" content="width=device-
width, initial-scale=1.0" />
<link rel="stylesheet" href="css/style.css"
/>
</head>
<body>
<div class="container">
<form action="signup.html"
method="post" id="signup">
<h1>Sign Up</h1>
<div class="field">
<label
for="name">Name:</label>
<input type="text" id="name"
name="name" placeholder="Enter your fullname" />
<small></small>
</div>
<div class="field">
<label
for="email">Email:</label>
<input type="text"
id="email" name="email" placeholder="Enter your email
address" />
<small></small>
</div>
<div class="field">
<button type="submit"
class="full">Subscribe</button>
</div>
</form>
</div>
<script src="js/app.js"></script>
</body>
</html>
Code language: HTML, XML (xml)

The HTML document references the style.css and app.js files. It uses
the <small> element to display an error message in case
the <input> element has invalid data.

Submitting the form without providing any information will result in


the following error:
Submitting the form with the name but invalid email address format
will result in the following error:

The following shows the complete app.js file:

// show a message with a type of the input


function showMessage(input, message, type) {
// get the small element and set the message
const msg =
input.parentNode.querySelector("small");
msg.innerText = message;
// update the class for the input
input.className = type ? "success" : "error";
return type;
}

function showError(input, message) {


return showMessage(input, message, false);
}

function showSuccess(input) {
return showMessage(input, "", true);
}

function hasValue(input, message) {


if (input.value.trim() === "") {
return showError(input, message);
}
return showSuccess(input);
}

function validateEmail(input, requiredMsg, invalidMsg)


{
// check if the value is not empty
if (!hasValue(input, requiredMsg)) {
return false;
}
// validate email format
const emailRegex =

/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]
+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-
9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-
Z]{2,}))$/;

const email = input.value.trim();


if (!emailRegex.test(email)) {
return showError(input, invalidMsg);
}
return true;
}

const form = document.querySelector("#signup");

const NAME_REQUIRED = "Please enter your name";


const EMAIL_REQUIRED = "Please enter your email";
const EMAIL_INVALID = "Please enter a correct email
address format";

form.addEventListener("submit", function (event) {


// stop form submission
event.preventDefault();

// validate the form


let nameValid = hasValue(form.elements["name"],
NAME_REQUIRED);
let emailValid =
validateEmail(form.elements["email"], EMAIL_REQUIRED,
EMAIL_INVALID);
// if valid, submit the form.
if (nameValid && emailValid) {
alert("Demo only. No form was posted.");
}
});

Code language: JavaScript (javascript)

How it works.

The showMessage() function

The showMessage() function accepts an input element, a message, and a


type:

// show a message with a type of the input


function showMessage(input, message, type) {
// get the <small> element and set the message
const msg =
input.parentNode.querySelector("small");
msg.innerText = message;
// update the class for the input
input.className = type ? "success" : "error";
return type;
}
Code language: JavaScript (javascript)

The following shows the name input field on the form:

<div class="field">
<label for="name">Name:</label>
<input type="text" id="name" name="name"
placeholder="Enter your fullname" />
<small></small>
</div>
Code language: HTML, XML (xml)

If the name’s value is blank, you need to get its parent first which is
the <div> with the class “field”.

input.parentNode
Code language: CSS (css)

Next, you need to select the <small> element:

const msg = input.parentNode.querySelector("small");


Code language: JavaScript (javascript)

Then, we update the message:

msg.innerText = message;

After that, we change the CSS class of the input field based on the
value of the type parameter. If the type is true, we change the class of
the input to success. Otherwise, we change the class to error.

input.className = type ? "success" : "error";


Code language: JavaScript (javascript)

Finally, return the value of the type:


return type;
Code language: JavaScript (javascript)

The showError() and showSuccess() functions

The the showError() and showSuccess() functions call the showMessage() function.
The showError() function always returns false whereas
the showSuccess() function always returns true. Also,
the showSuccess() function sets the error message to an empty string.

function showError(input, message) {


return showMessage(input, message, false);
}

function showSuccess(input) {
return showMessage(input, "", true);
}
Code language: JavaScript (javascript)

The hasValue() function

The hasValue() function checks if an input element has a value or not and
show an error message using the showError() or showSuccess() function
accordingly:

function hasValue(input, message) {


if (input.value.trim() === "") {
return showError(input, message);
}
return showSuccess(input);
}
Code language: JavaScript (javascript)

The validateEmail() function

The validateEmail() function validates if an email field contains a valid


email address:

function validateEmail(input, requiredMsg, invalidMsg)


{
// check if the value is not empty
if (!hasValue(input, requiredMsg)) {
return false;
}
// validate email format
const emailRegex =

/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]
+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-
9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-
Z]{2,}))$/;

const email = input.value.trim();


if (!emailRegex.test(email)) {
return showError(input, invalidMsg);
}
return true;
}
Code language: PHP (php)

The validateEmail() function calls the hasValue() function to check if the field
value is empty. If the input field is empty, it shows the requiredMsg.

To validate the email, it uses a regular expression. If the email is


invalid, the validateEmail() function shows the invalidMsg.

The submit event handler

First, select the signup form by its id using the querySelector() method:

const form = document.querySelector("#signup");


Code language: JavaScript (javascript)

Second, define some constants to store the error messages:

const NAME_REQUIRED = "Please enter your name";


const EMAIL_REQUIRED = "Please enter your email";
const EMAIL_INVALID = "Please enter a correct email
address format";
Code language: JavaScript (javascript)
Third, add the submit event listener of the signup form using
the addEventListener() method:

form.addEventListener("submit", function (event) {


// stop form submission
event.preventDefault();

// validate the form


let nameValid = hasValue(form.elements["name"],
NAME_REQUIRED);
let emailValid =
validateEmail(form.elements["email"], EMAIL_REQUIRED,
EMAIL_INVALID);
// if valid, submit the form.
if (nameValid && emailValid) {
alert("Demo only. No form was posted.");
}
});
Code language: JavaScript (javascript)

In the submit event handler:

1. Stop the form submission by calling the event.preventDefault() method.


2. Validate the name and email fields using
the hasValue() and validateEmail() functions.
3. If both name and email are valid, show an alert. In a real-world application,
you need to call the form.submit() method to submit the form.

Summary

 Use the <form> element to create an HTML form.


 Use DOM methods such as getDocumentById(), querySelector() to select
a <form> element. The document.forms[index] also returns the form element by
a numerical index.
 Use form.elements to access form elements.
 The submit event fires when users click the submit button on the form.

JavaScript - Animation
You can use JavaScript to create a complex animation having, but not limited to,
the following elements −
 Fireworks
 Fade Effect
 Roll-in or Roll-out
 Page-in or Page-out
 Object movements
You might be interested in existing JavaScript based animation
library: Script.Aculo.us.
This tutorial provides a basic understanding of how to use JavaScript to create
an animation.
JavaScript can be used to move a number of DOM elements (<img />, <div> or
any other HTML element) around the page according to some sort of pattern
determined by a logical equation or function.
JavaScript provides the following two functions to be frequently used in
animation programs.
 setTimeout( function, duration) − This function
calls function after duration milliseconds from now.
 setInterval(function, duration) − This function calls function after
every duration milliseconds.
 clearTimeout(setTimeout_variable) − This function calls clears any timer
set by the setTimeout() functions.
JavaScript can also set a number of attributes of a DOM object including its
position on the screen. You can set top and left attribute of an object to position
it anywhere on the screen. Here is its syntax.
// Set distance from left edge of the screen.
object.style.left = distance in pixels or points;

or

// Set distance from top edge of the screen.


object.style.top = distance in pixels or points;

Manual Animation
So let's implement one simple animation using DOM object properties and
JavaScript functions as follows. The following list contains different DOM
methods.
 We are using the JavaScript function getElementById() to get a DOM object
and then assigning it to a global variable imgObj.
 We have defined an initialization function init() to initialize imgObj where
we have set its position and left attributes.
 We are calling initialization function at the time of window load.
 Finally, we are calling moveRight() function to increase the left distance by
10 pixels. You could also set it to a negative value to move it to the left
side.

Example
<html>
<head>
<title>JavaScript Animation</title>
<script type = "text/javascript">
<!--
var imgObj = null;

function init() {
imgObj = document.getElementById('myImage');
imgObj.style.position= 'relative';
imgObj.style.left = '0px';
}
function moveRight() {
imgObj.style.left = parseInt(imgObj.style.left) + 10
+ 'px';
}

window.onload = init;
//-->
</script>
</head>

<body>
<form>
<img id = "myImage" src = "/images/html.gif" />
<p>Click button below to move the image to right</p>
<input type = "button" value = "Click Me" onclick =
"moveRight();" />
</form>
</body>
</html>

Automated Animation
In the above example, we saw how an image moves to right with every click. We
can automate this process by using the JavaScript function setTimeout() as
follows −
Here we have added more methods. So let's see what is new here −
 The moveRight() function is calling setTimeout() function to set the
position of imgObj.
 We have added a new function stop() to clear the timer set
by setTimeout() function and to set the object at its initial position.

Example
<html>
<head>
<title>JavaScript Animation</title>
<script type = "text/javascript">
<!--
var imgObj = null;
var animate ;

function init() {
imgObj = document.getElementById('myImage');
imgObj.style.position= 'relative';
imgObj.style.left = '0px';
}
function moveRight() {
imgObj.style.left = parseInt(imgObj.style.left) + 10
+ 'px';
animate = setTimeout(moveRight,20); // call
moveRight in 20msec
}
function stop() {
clearTimeout(animate);
imgObj.style.left = '0px';
}

window.onload = init;
//-->
</script>
</head>

<body>
<form>
<img id = "myImage" src = "/images/html.gif" />
<p>Click the buttons below to handle animation</p>
<input type = "button" value = "Start" onclick =
"moveRight();" />
<input type = "button" value = "Stop" onclick = "stop();"
/>
</form>
</body>
</html>

Rollover with a Mouse Event


Here is a simple example showing image rollover with a mouse event.
Let's see what we are using in the following example −
 At the time of loading this page, the ‘if’ statement checks for the existence
of the image object. If the image object is unavailable, this block will not
be executed.
 The Image() constructor creates and preloads a new image object
called image1.
 The src property is assigned the name of the external image file called
/images/html.gif.
 Similarly, we have created image2 object and assigned /images/http.gif in
this object.
 The # (hash mark) disables the link so that the browser does not try to go
to a URL when clicked. This link is an image.
 The onMouseOver event handler is triggered when the user's mouse
moves onto the link, and the onMouseOut event handler is triggered when
the user's mouse moves away from the link (image).
 When the mouse moves over the image, the HTTP image changes from the
first image to the second one. When the mouse is moved away from the
image, the original image is displayed.
 When the mouse is moved away from the link, the initial image html.gif will
reappear on the screen.
<html>

<head>
<title>Rollover with a Mouse Events</title>

<script type = "text/javascript">


<!--
if(document.images) {
var image1 = new Image(); // Preload an image
image1.src = "/images/html.gif";
var image2 = new Image(); // Preload second
image
image2.src = "/images/http.gif";
}
//-->
</script>
</head>

<body>
<p>Move your mouse over the image to see the result</p>

<a href = "#" onMouseOver = "document.myImage.src =


image2.src;"
onMouseOut = "document.myImage.src = image1.src;">
<img name = "myImage" src = "/images/html.gif" />
</a>
</body>
</html>

How to Toggle Password Visibility


A password field provides a way for the users to securely input a password by
showing the * character instead of the actual characters.

However, it is likely that some users will type the wrong password. To help them
see the password that they’re currently entering, you can add a button that allows
them to toggle the visibility of the password.

To make the password visible, you can follow these steps:

 First, create an <input> element with the type of password and an icon that
allows users to click it to toggle the visibility of the password.
 Second, bind an event handler to the click event of the icon. If the icon is
clicked, toggle the type attribute of the password field
between text and password. The input with the type text will show the actual
password.
 Third, change the icon to make it more user-friendly. This step is optional.

To make it easy, we’ll use two icons from the Bootstrap icon for toggling the
visibility of the password.

The following shows the HTML code of the page:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-
scale=1.0" />
<title>Toggle Password Visibility</title>
<link rel="stylesheet"
href="https://cdn.jsdelivr.net/npm/bootstrap-
icons@1.3.0/font/bootstrap-icons.css" />
<link rel="stylesheet" href="css/style.css" />
</head>
<body>
<div class="container">
<h1>Sign In</h1>
<form method="post">
<p>
<label for="username">Username:</label>
<input type="text" name="username" id="username">
</p>
<p>
<label for="password">Password:</label>
<input type="password" name="password" id="password"
/>
<i class="bi bi-eye-slash" id="togglePassword"></i>
</p>
<button type="submit" id="submit" class="submit">Log
In</button>
</form>
</div>
<script src="js/app.js"></script>
</body>
</html>
Code language: HTML, XML (xml)

The HTML page contains an input element with the type password and
an <i> element with the CSS classes provided by Bootstrap.

The Bootstrap allows you to use the class bi-eye of the <i> element to show the eye
icon. To change the icon from eye to eye slash, you just need to change the class
of the <i> element to bi-eye-slash

To place the icon inside the password input, you can use the negative margin for
the <i> element as follows:

form i {
margin-left: -30px;
cursor: pointer;
}
Code language: CSS (css)

The rest of the CSS is straightforward.


In the app.js file:

First, select the toggle password icon and the password input field using
the querySelector() method:

const togglePassword =
document.querySelector('#togglePassword');
const password = document.querySelector('#password');
Code language: JavaScript (javascript)

Then, attach an event listener to the togglePassword icon and toggle the type attribute
of the password field as well as the class of the icon:

togglePassword.addEventListener('click', function (e) {


// toggle the type attribute
const type = password.getAttribute('type') === 'password' ?
'text' : 'password';
password.setAttribute('type', type);
// toggle the eye / eye slash icon
this.classList.toggle('bi-eye');
});
Code language: JavaScript (javascript)

You might also like