Home » Posts tagged 'javascript'

Tag Archives: javascript

Form Handling and Validation in JavaScript

HTML form validation can be done with JS.

Form validation normally used on the server, after the user had fill up all the data and then hit the submit button.

If the data entered by a user was incorrect or was something missing, the server will send all the data back to the user and request that the form need to be resubmitted with correct information.

JS provides a way to validate form’s data on the user’s computer before sending it to the web server. In Form validation, there will be two functions.

  • Basic − the form will checked to make sure all the mandatory fields are filled in. It would require just a loop in the form and check for data.
  • Data Format − the data must be checked for correct form and value. Developer’s code must include with logic to test correctness of data.

Different types of form validation

There are two types of validation:

Client-side validation is validation that occurs before the data has been submitted to the server.

Client side validation is performed by a web browser, before input is sent to a web server.

Client side validation check data and then send to server in avoid  unnecessary server call

Server-side validation is validation which occurs after the data has been submitted.

This is performed by a web server, after input has been sent to the server.

A response is sent back to the user to tell what corrections to make,If the data fails authentication.

EXAMPLE

OUTPUT

Form field (firstname) is empty, so the function alerts a message, and returns false value.

Data Validation

Data validation is the process for ensuring that user input is clean, correct.

Validation tasks are:

  • Is user filled in all required fields?
  • Is user entered a valid date?
  • Is user entered text in a numeric field?

Some Validation HTML Input Attributes:

Disabled – This is specifies that the input element should be disabled

Max – This is specifies the maximum value of an input element

Min – This is specifies the minimum value of an input element

Pattern – This is specifies the value pattern of an input element

Required – This is specifies that the input field requires an element

Type – This is specifies the type of an input element

Form Example

Cookies in JavaScript

What are Cookies?

Normally, Cookies store user information in small text files.on your computer.

A cookie is a piece of data that is stored on your browser to be accessed by your browser. Cookies are also saved as key/value pairs.

Cookies will remember information about the user, when server forgets everything about the user after the connection is shut down.

  • When a user visits a web page, The name of user can be stored in a cookie.
  • Next time the user visits the page, the cookie “remembers” the name.

How It Works ?

Server sends some data to the visitor’s browser in the form of a cookie. The browser may accept the cookie. When the visitor go to another page, the browser sends the same cookie to the server.

Cookies are a plain text data record of 5 variable −

  • Expires − The date the cookie will expire
  • Domain − The domain name of thewebsite.
  • Path − The path to the directory or web page that set the cookie.
  • Secure − The cookie may only be retrieved with a secure server.
  • Name value – Cookies are set and retrieved in the form of key-value pairs

Create a Cookie with JavaScript

JS can create, read, and delete cookies with the document.cookie property.

A cookie can be created like this:

document.cookie = “username=Ram Das”;

Example

Read a Cookie with JavaScript

With JS, cookies can be read like this:

var x = document.cookie;

Example

Change a Cookie with JavaScript

With JS, cookies can be changed like this:

document.cookie = “username=John Smith; expires=Thu, 18 Dec 2013 12:00:00 UTC; path=/”;

Example

In this example the cookie extend the expiry date by 1 Month.

Delete a Cookie with JavaScript

With JS, cookies can be delete like this:

Just set the expires parameter to a passed date:

document.cookie = “username=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;”;

Example

 Full Example

DOM in JavaScript

The DOM is an object-oriented representation of the website pages, which is modified with a scripting language JS.

The DOMstand for Document Object Model.

When a web page is loaded, the browser creates a DOM of the page.

The DOM model is a tree of Objects.

The DOM is a platform that allows programs and scripts to dynamically access and update the content and style of a document.

It is a programming interface for HTML and XML documents. It represents the document as nodes and objects.

With the object model, JS will have all the power to create dynamic HTML:

  • It can be change all the HTML elements in the page
  • It can bechange all the HTML attributes in the page
  • It can bechange all the CSS styles in the page
  • It can be remove existing HTML elements and attributes
  • It can be add new HTML elements and attributes
  • It can be react to all existing HTML events in the page
  • It can be create new HTML events in the page

The DOM standard is separated into three different parts:

  • Core DOM – For all document types
  • XML DOM – For XML documents
  • HTML DOM – For HTML documents

For example, the standard DOM specifies that

the getElementsByTagName method must return a list of all the <P> elements in the document.

varpara = document.getElementsByTagName(“P”);

alert(para[0].nodeName);

How Can Access the DOM?

There is nothing special to begin using the DOM.

Different implementations of the DOM will be happened in different browsers.

Every web browser uses some document object model to make web pages accessible via JavaScript.

That DOM programming can be simple as it is displays an alert message by using the alert() function from the window object.

For Example

<body onload=”window.alert(‘Welcome to my home page!’);”>

When creating a script , whether it’s inline in a <script> element , you can immediately using the API for the document or window elements to manipulate the document.

Example

From where the DOM came?

The DOM originated as a specification to allow JS and Java programs to be portable among web browsers.

Dynamic HTML was the immediate ancestor of the DOM, and it was originally thought of largely in terms of browsers.

However, when the DOM Working Group was formed, it was also joined by vendors in other domains, including HTML or XML editors and document repositories.

DOM Tree of Objects

Document –

Root element(html) –

          Element(head) –

                   Element(title)

                   Text(My Title)

          Element(body) –

                   Element(a) –

                             Attribute(href)

                             Text (My Link)

                   Element(h1) –

                             Text(My Header)

Example with DOM Method

OUTPUT

Finding DOM HTML Element by Id

Hello World!

This example demonstrates the getElementsById method.

OUTPUT

This example demonstrates the getElementsById method.

The text from the intro paragraph is Hello World!

This Keyword in JavaScript

This keyword refers to an object, that object which is executing the current bit of JavaScript code.

JavaScript function while executing has a reference to its current execution any function, called this.

JavaScript function while executing has a reference to its current execution any function, called this.

with this keyword,It does not matter how and where function is declared or defined.

Example

function’s this keyword behaves differently in JavaScript compared to other language.

In most of cases, this is determined that by how avalue of function is called.

It cannot be set by assignment on time execution, and it will be different each time the function is called.

ES5 have the bind() method to set the value of a function’s this regardless of how it’s called, and ES2015 introduced arrow functions which don’t provide their own this binding.

Example

This keyword has some different values depending on its usage:

  • Within a method, this keyword refers to the owner object.
  • As Single, this keyword refers to the global object.
  • this keyword within a function refers to the global object.
  • Within a function, within strict mode, this keyword is undefined.
  • Creating an event, this keyword refers to the element that received the event.
  • Methods like call(), and apply() can refer this to any object.

In an object method, this refers to the “owner” of the method.

In the example on the top of this page, this refers to the person object.

The person object is the owner of the fullName method.

Example

OUTPUT

This in Event Handlers

In HTML event handlers, this refers to the HTML element that received the event:

This in a Function (Default)

The owner of the function is the default binding for this.

Within function, this keyword refers to the Global object.

OUTPUT

Global Scope

If a function uses ‘this’ keyword, is called from the global scope then this will point to the window object

OUTPUT

Example: this keyword inside inner function

OUTPUT

Strict Mode in JavaScript

JAVACRIPT’s strict mode, introduced in ECMAScript 5, is a way to opt in to a restricted variant of JAVACRIPT.

Strict mode is not just a subset: it intentionally has different semantics from all other normal code.

Some browsers does not support strict mode.

To run strict mode code with different behavior from browsers need to test for support for the relevant aspects of strict mode.

Strict mode code and non-strict mode code can be co existing, so scripts can opt into strict mode incrementally

Strict mode makes many changes to normal JavaScript semantics:

  1. Eliminates some JavaScript silent errors by changing them to throw errors.
  2. Fixes mistakes that make it difficult for JavaScript engines to perform optimizations: strict mode code can sometimes be made to run faster than identical code that’s not strict mode.

The “use strict”; Syntax

For declaring strict mode the syntax was designed to be compatible with of JS.

Compiling a numeric literal (10 + 15;) or a string literal (“Ram Das”;) in a JS program has no side effects.

It will simply compiles to a non existing variable and it will dies.

Keywords reserved for future JavaScript versions can NOT be used as variable names in strict mode

These are:

  • implements
  • interface
  • let
  • package
  • private
  • protected
  • public
  • static
  • yield

Simplifying variable uses

Strict mode simplifies how variable names map to particular variable definitions in code.

This is critical to fully optimizing JS code.

JS makes this basic mapping of name to variable definition in the code impossible to perform until runtime.

Strict mode will removes most cases where it will happens, so the compiler can better optimize strict mode code.

First, strict mode prohibits with.

The problem with with is that any name inside the block might map either to a property of the object passed to it, or to a variable in surrounding (or even global) scope, at run time, Strict mode makes with a syntax error, so there’s no chance for a name in a with to refer to an unknown location at run time.

Example

JavaScript allows strictness of code using “use strict”. Write “use strict” at the top of JavaScript code or in a function to run strict mode.

Example

Output

Defines that JavaScript code should be executed in “strict mode”.

“use strict” is to indicate, the code should be executed within “strict mode”.

Declaring Strict Mode

Strict mode is declared by adding “use strict”; to the beginning of a script or a function.

Example

Declared inside a function

Hoisting in JavaScript

What is Hoisting?

Hoisting is when the JavaScript interpreter moves all variable and function declarations to the top of the current scope.

Hoisting is done during the interpreter’s first run through the code.

The important thing is that the actual declarations are hoisted, and that assignments will be left where they are.

Hoisting is a JS mechanism where variables and functions are declarations are moved to the top before code execution.

All functions and variables that are declared are moved to the top of their scope regardless of whether their scope is global or local.

Of note however, is the fact that the hoisting mechanism only moves the declaration. The assignments are left in place.

Variable declarations are one of the most common aspects of any programming language.

However, JavaScript has a little quirk, known as hoisting, which can turn an innocent declaration into a subtle bug.

The variable and function declarations are put into memory during the compile phase ,  and a hoisting suggests that variable and function declarations are moved to the top of code..

Always Declare Variables At the Top !Hoisting is (to many developers) an unknown or overlooked behavior of JavaScript.

To avoid bugs, always declare all variables at the beginning of every scope.

Example

Variable Declarations

This is a basic example:

Function Declarations

Hoisting also applies to function declarations.

This is a basic example:

Function Hoisting

Function declarations are also be hoisted. But that functions, what assigned to variables, that’s are not hoisted.

For example, the following code will work due to function declaration hoisting.

The variable declaration for foo is hoisted before the function call.

However, since the assignment to bar is not hoisted, an exception is thrown for trying to call a non-function variable.

Conclusion

Hoisting is an easy to understand, but often overlooked nuance.

To help avoid these bugs, many developers advocate for a single variable declaration statement at the very beginning of every scope.

Hoisting is JS’s default behavior of moving declarations to the top.

JavaScript Declarations are Hoisted

In JS, a variable can be declared after it has been used.

A variable can be used before it has been declared.

Example 1 does not give the same result as Example 2:

Example 1

Output

Example 2

Data Object in JavaScript

The Date object is a datatype, Date objects are created with the new Date( ), Most of “Date” methods simply allow you to get and set the year, month, day, hour, minute, second.

If no arguments are provided, the constructor creates a JavaScript Date object for the current date and time according to system settings for timezone offset.

JavaScript can represent date and time till the year 275755.

Syntax

Date Properties

Date.properties-It will allows the addition of properties to a Date object.

Date.length– This property will find the length of date and display the value of Date.length. This is the number of arguments which is handled by the constructor.

Date Methods

Sr No Mathod Description
1 Date() It will return today’s date and time
2 getDate() It will return the day of the month for the specified date as per local time.
3 getDay() It will return the day of the week for the specified date as per local time.
4 getFullYear() It will return the year of the specified date as per local time
5 getHours() It will return the hour in the specified date as per local time.
6 getMilliseconds() It will return the milliseconds in the specified date as per local time.
7 getMinutes() It will return the minutes in the specified date as per local time
8 getMonth() It will return the month in the specified date as per local time.
9 getSeconds() It will return the seconds in the specified date as per local time.
10 getTime() It will return the numeric value of the specified date as the number of milliseconds
11 getTimezoneOffset() It will return the time-zone offset in minutes for the current locale
12 getYear() It will returns the year in the specified date of local time
13 setDate() It will sets the day of the month for a specified date of local time.
14 setFullYear() It will set the full year for a specified date of local time.
15 setHours() It will set the hours for a specified date of local time
16 setMilliseconds() This method is forsets the milliseconds for a specified date of local time.
17 setMinutes() This method is used to set the minutes for a specified date of local time
18 setMonth() This method is used to set the month for a specified date of local time.
19 setSeconds() This method is used to set the seconds for a specified date of local time.
20 setTime() This method is used to set the Date object to the time represented by a number of milliseconds.

Math Object in JavaScript

The JavaScript Math object used to perform mathematical tasks with numbers.Math is an object that has properties and methods.

Math has no constructor. All Math’s properties and methods are static.

To refer methods and properties use Math.propertName  and functions as Math.funcationName().

For example to access the constant pi use Math.PI

To call the sine function use Math.sin(valuex), where valuex is a argument. Constants are defined with the full precision of real numbers.

The math object provide properties and methods of constants and functions for mathematical.

Math’s properties and methods can be called by using Math as an object without creating it.

Syntax

Example

Math Properties (Constants)

Property Description
E It will return Euler’s number (approx. 2.718).
LN2 It will return tde natural logaritdm of 2 (approx. 0.693)
LN10 It will return tde natural logaritdm of 10 (approx. 2.302)
LOG2E It will return tde base-2 logaritdm of E (approx. 1.442)
LOG10E It will return tde base 10 logaritdm of E (approx. 0.434)
PI It will return constant value of PI (approx. 3.14)
SQRT1_2 It will return tde square root of 1/2 (approx. 0.707)
SQRT2 It will returnstde square root of 2 (approx. 1.414)

Math Object Methods

Mathod Description
abs(valuex) It will return the absolute value of valuex
acos(valuex) It will return the arccosine of valuex, in radians
asin(valuex) It will return the arcsine of valuex, in radians
atan(valuex) It will return the arctangent of valuex as a numeric value between -PI/2 and PI/2 radians
atan2(valuey, valuex) It will return the arctangent of the quotient of its arguments
ceil(valuex) It will return the value of valuex rounded up to its nearest integer
cos(valuex) It will return the cosine of valuex (valuex is in radians)
exp(valuex) It will return the value of Ex
floor(valuex) It will return the value of valuex rounded down to its nearest integer
log(valuex) It will return the natural logarithm (base E) of valuex
max(valuex,value y, valuez, …, valuen) It will return the number with the highest value
min(valuex,valuey, valuez, …, valuen) It will return the number with the lowest value
pow(valuex, valuey) It will return the value of valuex to the power of valuey
random() It will return a random number between 0 and 1
round(valuex) It will return the value of valuex rounded to its nearest integer
sin(valuex) It will return the sine of valuex (valuex is in radians)
sqrt(valuex) It will return the square root of valuex
tan(valuex) It will return the tangent of an angle

Global in JavaScript

Global scope is a JavaScript function Scope.Scope determines the accessibility (visibility) of variables.

Variables defined inside a function are not accessible (visible) from outside the function.

A global variable is declared outside the function or declared with an object. It can be accessed from any function.

Declaring global variable within function

To declare global variables within a function, we need to use window object. For example:

Now this value can declared with in any function and can be access and used from any function.

For example:

EXAMPLE

OUTPUT

Internals of global variable

On outside a function,when a variable declare, that will add in window object. So it can be access through window object.

For example:

Global JavaScript Variables

If any variable declared outside a function, so that will becomes GLOBAL.

A global variable has global scope: All scripts and functions on a web page can access it. 

OUTPUT

Automatically Global

If a value assign to a variable that has not been declared, it will automatically turn on GLOBAL variable.

This example will declare a global variable myName, the value is assigned inside a function.

OUTPUT

Global Variables in HTML

With JavaScript, the global scope is the complete
JavaScript environment.

In HTML, the global scope is the window object. All global variables belong to the window object.

OUTPUT

Global Properties

Property Description
Infinity A numeric value that represents positive/negative infinity
NaN “Not-a-Number” value, It means there is nothing like value.
undefined This property indicates that a variable will not assigned a value.

Global Functions

Function Description
decodeURI() It will decodes a URI
decodeURIComponent() It will decodes a URI component
encodeURI() It will encode a URI
encodeURIComponent() It will encode a URI component
escape() It will use encodeURI() or encodeURIComponent() instead
eval() It willevaluates a string and executes it as if it was script code.
isFinite() It will determine whether a value is a finite, normal number
Number() It will convert an object’s value to a number
parseFloat() It will parse a string and returns a floating point number
parseInt() It will parse a string and returns an integer
String() It will convert an object’s value to a string
unescape() It will use decodeURI() or decodeURIComponent() instead

Functions in JavaScript

What is a Function?

  • A function is a block of code or a subprogram designed to perform a particular task.
  • Function is executed only when it is called. This is called invoking/calling a function. Thus it eliminates writing the same code again and again.
  • Values can be passed into functions and used within the function body.

Function always returns a value, if no return type is specified, the function will return undefined .

JavaScript Function Syntax

JavaScript supports 4 types of function invoking:

  1. Function having no arguments and no return value
  2. Function having arguments and no return value
  3. Function having return value and argument(s)
  4. Function having return value but no arguments

Function having no arguments and no return value

In JavaScript, if there’s no specified return type, the function will return undefined. Consider the following example:

R

Result

Function having arguments and no return value

Consider the following example:

Result

Here the ‘return’ statement is missing. But arguments are passed to the function and used in the block of code.

Function having return value and arguments

Result

Function having return value but no arguments

Result

Managed by MochaHost - Fast & Easy WordPress Hosting