Replace/Append Cookies in JavaScript

Replace/Append Cookies

When we assign a new cookie value to document.cookie, the current cookie is not replaced. The new cookie is parsed and its name-value pair is appended to the list. The exception is when you assign a new cookie with the same name (and same domain and path, if they exist) as a cookie that already exists. In this case, the old value is replaced with the new.

Reading Cookie

We can read cookies by a document.cookie. The problem occurs when we need the specific part of the cookie to perform some action.

Deleting Cookies

A cookie is deleted by setting a cookie with the same name (and domain and path, if they were set) with an expiration date in the past and if using max-age then must set a negative value.

Ex:

Updating Cookies

A cookie is possible to update by setting a new value to a cookie with the same name.

Cookies Security Issues

  • Can misuse Client Details
  • Can track User
  • Client Can Delete Cookies
  • Client can Manipulate Cookies

Cookies Limitation

  • Support HTML4 / HTML 5
  • Each cookie can contain 4kb Data
  • Cookies can be stored in Browser and server
  • It is sent with each request
Tagged : / / /

How many create cookies in JavaScript?

JavaScript Cookies

Cookies are exposed as the cookie property of the Document object. This property is both readable and writeable.

You can see Cookies in Google Chrome by following chrome://settings/content/cookies

Creating Cookies

When you assign a string to document.cookie, the browser parses it as a cookie and adds it to its list of cookies. There are several parts to each cookies, many of them optional.

Syntax: –

document.cookie = “name=value”;
document.cookie = “name=value; expires=date; domain=domain; path=path; secure”;
document.cookie = “name=value; max-age=inSecond; domain=domain; path=path; secure”;

Ex:-

Creating Cookies

Optional Cookies Attribute:-

max-age
expires
domain
path
secure

Whenever you omit the optional cookie fields, the browser fills them in automatically with reasonable defaults.

max-age

It is used to create persistent cookies. It is supported by all modern browsers except IE.

Type of cookies: –

  • Session Cookies – Cookies that are set without the expires/max-age field are called session cookies. It is destroyed when the user quits the browser.
  • Persistent Cookies – The browser keeps it up until their expiration date is reached.

Ex:-

expires

It is used to create persistent cookies.

Type of cookies: –

  • Session Cookies – Cookies that are set without the expires/max-age field are called session cookies. It is destroyed when the user quits the browser.
  • Persistent Cookies – The browser keeps it up until their expiration date is reached.

Ex:-

document.cookie = “username=devops; expires=Monday, 3-Sep-2018 09:00:00 UTC”;

domain

It specifies the domain for which the cookie is valid. If not specified, this defaults to the host portion of the current document location. If a domain is specified, subdomains are always included.

Ex: –

path

Path can be / (root) or /mydir (directory). If not specified, defaults to the current path of the current document location, as well as its descendants.

Ex: – document.cookie = “username=devops; path=/”;

Ex: – document.cookie = “username=devops; path=/home”;

secure

Cookie to only be transmitted over secure protocol as https. Before Chrome 52, this flag could appear with cookies from http domains.

Ex: – document.cookie = “username=devops; secure”;

Tagged : / / / / /

What are cookies in JavaScript?

Cookies

A cookie is a small piece of text data set by the Web server that resided on the client’s machine. Once it’s been set, the client automatically returns the cookie to the webserver with each request that it makes. This allows the server to place values it wishes to ‘remember’ in the cookie, and have access to them when creating a response.

How Cookie Works

How Cookie Works

How Cookie Works

How Dangerous Cookies are

Type of Cookies

  • Session Cookies – Cookies that are set without the expires field are called session cookies. It is destroyed when the user quits the browser.
  • Persistent Cookies – The browser keeps it up until their expiration date is reached.
Tagged : / / /

How to add placeholder to select2.js

Single select placeholders

<select class="js-example-placeholder-single js-states form-control">
  <option></option>
</select>

$(".js-example-placeholder-single").select2({
    placeholder: "Select a state",
    allowClear: true
});

Multi-select placeholders

<select class="js-example-placeholder-multiple js-states form-control" multiple="multiple"></select>
$(".js-example-placeholder-multiple").select2({
    placeholder: "Select a state"
});

Using placeholders with AJAX

Select2 supports placeholders for all configurations, including AJAX. You will still need to add in the empty <option> if you are using a single select.

When using Select2 in single-selection mode, the placeholder option will be passed through the templateSelection callback if specified. You can use some additional logic in this callback to check the id property and apply an alternative transformation to your placeholder option:

$('select').select2({
  templateSelection: function (data) {
    if (data.id === '') { // adjust for custom placeholder values
      return 'Custom styled placeholder text';
    }

    return data.text;
  }
});
Tagged : /

Accessing Form Fields in JavaScript

Accessing Form

JavaScript provides various ways of accessing form:-

  • document.forms[index_number] – It returns collection of form in the documents.
  • document.forms[“name_attribute_value”] – we can use name attribute of the form.
  • document.name_attribute_value – we can use name attribute of the form with dot as well.
  • getElementById(“ID”) – If form as an unique id we can use it.

Accessing Form Fields

If form fields have unique ID then it is possible to access them using the getElementById( ) method. However, There are some other ways: –

  • elements[ ] – It contains collection of form fields.

Syntax: –

document.form_name.elements[index_number];
document.form_name.elements[“name_attribute_value”];
document.form_name.name_attribute_value;
document.form_name.ID_attribute_value;

  • getElementsByName(“field_name”) – This method is also used to access form field.
Tagged : / / /

How to use Form Handling in javascript

Form Handling

JavaScript provides access to the forms within an HTML document through the Form object known as HTMLFormElement in the DOM. Which is a child of the Document Object.

Properties

PropertiesValueDescription
accept-charsetUTF-8Specifies the charset used in the submitted form (default: the page charset).
actionURLContains a URL that defines where to send the data after submitting the form
autocompleteOn (default)
Off
Determines that the browser retains the history of previous values.
enctypespecifies how the browser encodes the data before it sends it to the server. (default: is url-encoded).
encodingHolds the value of the enctype attribute, which usually contains either application/x-www-form-urlencoded value or the multipart/form-data value (in the case of file upload)
elements[ ]An array of DOM elements that correspond to the interactive form fields within the form

Properties

PropertiesValueDescription
lengthThe number of a form field with a given form tag. Should bt the same as elements.length
methodGET (default)
POST
Specifies how to send the form data to a web server. The data can be sent as URL variables, by using the get method or as HTTP post, by using the post method
namenameSpecifies a name used to identify the form
novalidatenovalidateSpecifies that the browser should not validate the form.
target_self (default)
_blank
_parent
_top
framename
Specifies the target of the address in the action attribute

Methods

MethodDescription
checkValidity ( )Returns a true or false value indicating whether or not all the fields in the form are in a valid state.
reset ( )Returns all form fields to their initial state.
submit ( )Submits the form to the URL specified in the form’s action attribute

Events: –

  • onreset
  • onsubmit
Tagged : / / / / / / /

What is the difference between a timeout and an interval in Javascript?

setTimeout( ) Method

The setTimeout() method sets a timer which executes a function or specified piece of code once after the timer expires. The function is only executed once. It returns a positive integer value which identifies the timer created by the call to setTimeout(); this value can be passed to clearTimeout() to cancel the timeout.

Syntax: –
setTimeout (function, milliseconds, para1, para2);
Ex: – var timeoutID = setTimeout(show, 2000);

clearTimeout( ) Method

The clearTimeout() method cancels a timeout previously established by calling setTimeout(). The ID value returned by setTimeout() is used as the parameter for the clearTimeout() method.

Syntax: – clearTimeout (timeoutID);

Ex: – clearTimeout(timeoutID);

setInterval( ) Method

The setInterval() method repeatedly calls a function or executes a code snippet, with a fixed time delay between each call. It returns an interval ID that uniquely identifies the interval, so you can remove it later by calling clearInterval().

Syntax: – setInterval (function, milliseconds, para1, para2);

Ex: – var intervalID = setInterval(show, 2000);

clearInterval( ) Method

The clearInterval() method cancels a timed, repeating action that was previously established by a call to setInterval().

Syntax: – clearInterval (intervalID);

Ex: – clearInterval(intervalID);

Tagged : / / / / / /

History Object and Location Object in javascript?

History Object

The History object is a read-only array of URL strings that shows where the user has been recently.

Syntax: –

window.history.property

window.history.method

Property

  • length – It returns the number of URLs in the history list.

Methods

  • back ( ) – It loads the previous URL in the history list.
  • forward ( ) – It loads the next URL in the history list.
  • go ( ) – It access a particular item in the history list relative to the current position. Using a negative value moves to a history item previous to the current location, while a positive number moves forward in the history list.

Location Object

This is used to access the current location (URL) of the window. The Location object can be both read and replaced, so it is possible to update the location of a page through scripting. Location object is a property of Window.

Syntax:-

window.location.property

window.location.method

Properties

  • hash – The part of the URL including and following the # symbol.
  • host – The hostname and port number.
  • hostname – hostname
  • href – entire URL
  • pathname – Path relative to the host.
  • port – Port Number
  • protocol – Protocol of URL
  • search – The part of the URL including and after the ?

Methods

  • assign(URL) – It changes the location of current page with the passed in URL.
  • reload( ) – Reload the current page.
  • replace (URL) – Replaces the current page with the given URL in history. As it is replaced in history, it won’t be possible to access the current page with back/forward.
Tagged : / / / /

Moving Windows in JavaScript

Moving Windows

moveBy ( ) – This method moves the current window by a specified amount of pixels.

Syntax:- window.moveBy(horizontalPixels, verticalPixels);

Where,

window – It is the name of the window to move or is called just window if it is the main window.

horizontalPixels – It is the number of horizontal pixels to move the window where positive numbers move the window to the right and negative numbers to the left.

verticalPixels – It is the number of vertical pixels to move the window where positive number move the window down and negative number up.

Ex:- newWindow.moveBy(200, 200);

Moving Windows

moveTo ( ) – This method moves the window to the specified coordinates.

Syntax:- window.moveTo(x, y);

Where,

window – It is the name of the window to move or is called just window if it is the main window.

x – It is the screen co-ordinate on the x-axis to move the window to.

y – It is the screen co-ordinate on the y-axis to move the window to.

Ex:- newWindow.moveTo(200, 200);

Resizing Windows

Resizing Windows

resizeBy ( ) – This method is used to resize the current window by a certain amount, relative to its current size. 

Syntax:- window.resizeBy(width, height);

Where,

window – It is the name of the window to move or is called just window if it is the main window.

width – It is the number of width pixels, where positive numbers increase the window and negative numbers decrease.

height – It is the number of height pixels, where positive numbers increase the window and negative numbers decrease.

Ex:- newWindow.resizeBy(200, 200);

Resizing Windows

resizeTo ( ) – This method is used to resize a window to the specified width and height.

Syntax:- window.resizeTo(width, height);

Where,

window – It is the name of the window to move or is called just window if it is the main window.

width – It is an integer representing the new outerWidth in pixels (including scroll bars, title bars, etc).

height – It is an integer value representing the new outerHeight in pixels (including scroll bars, title bars, etc).

Ex:- newWindow.resizeTo(200, 200);

Scrolling Windows

scrollBy ( ) – This method scrolls the document in the window by the given amount.

Syntax:- window.scrollBy(x, y); or window.scrollBy(options);

Where,

window – It is the name of the window to scroll or is called just window if it is the main window.

x – How many pixels to scroll by, along the x-axis (horizontal). Positive values will scroll to the right, while negative values will scroll to the left

y – How many pixels to scroll by, along the y-axis (vertical). Positive values will scroll down, while negative values scroll up

Options – It is an object with three possible properties:
top, which is the same as the y-coord
left, which is the same as the x-coord
behavior, which is a string containing one of smooth, instant, or auto; default is auto

Note – For this method to work, the visible property of the window’s scrollbar must be set to true!

Scrolling Windows

scrollTo ( ) – This method scrolls to a particular set of coordinates in the document.

Syntax:- window.scrollTo(x, y); or window.scrollTo(options);

Where,

window – It is the name of the window to scroll or is called just window if it is the main window.

x – It is the pixel along the horizontal axis of the document that you want to be displayed in the upper left.

y – It is the pixel along the vertical axis of the document that you want to be displayed in the upper left.

options is an object with three possible properties:
top, which is the same as the y-coord
left, which is the same as the x-coord
behavior, which is a string containing either smooth, instant, or auto; default is auto

Tagged : / / / /

What is a window object in JavaScript? What are its properties?

Window Object

  • Window object represents the browser’s window or potentially frame, that a document is displayed in.
  • As long as a browser window is open, even if no document is loaded in the window, the window object is defined in the current model in memory.
  • All global JavaScript variables, functions and objects automatically become members of the window object.

Dialog boxes

It is used to provide some information to users.

Type of Dialog box:-

  • Alert
  • Confirm
  • Prompt

alert ( ) Method

This Window object’s method is used to display data in the alert dialog box. alert really should be used only when you truly want to stop everything and let the user know something.

Syntax:- window.alert( ) or alert ( )

confirm ( ) Method

This Window object’s method is used to display a message for a user to respond to by pressing either an OK button to agree with the message to a Cancel button to disagree with the message. It returns true on OK and false on Cancel.

Syntax:- window.confirm( ) or confirm ( )

prompt ( ) Method

Window object’s method prompt() can be used to get input from the user, named prompt. The prompt( ) method displays a dialog box that prompts the visitor for input.

Once the prompt function obtains input from the user, it returns that input. If the user press the cancel button in the dialog or close box, a value null will be returned.

Syntax: – prompt(text, defaultText)

open ( ) Method

The open( ) method creates a new secondary browser window, similar to choosing New Window from the File menu. It returns a Window object representing the newly-created window. If the window couldn’t be opened, the returned value is instead null.

Syntax: – window.open (URL, name, features, replace)

URL – URL indicates the document to load into the window. If no URL is specified, a new window with about: blank is opened

Name – Specifies the target attribute or the name of the window. The following values are supported:

_blank – URL is loaded into a new window. This is default
_parent – URL is loaded into the parent frame
_self – URL replaces the current page
_top – URL replaces any framesets that may be loaded

open ( ) Method

Syntax: – window.open (URL, name, features, replace)

Features – It is a comma-delimited string that lists the features of the window.

Replace – It indicates whether or not the URL specified should replace the window’s contents. This would apply to a window that was already created. Value can be true/false.

Features

Feature ParameterValueExample
alwaysLoweredyes/noalwaysLowered=yes
alwaysRaisedyes/noalwaysRaised=no
centerscreenyes/nocenterscreen=yes
chromeyes/nochrome=yes/true
closeyes/noclose=no
dialogyes/nodialog=yes
dependentyes/nodependent=yes
z-lockyes/noz-lock=yes
hotkeysyes/nohotkeys=yes

Features

Feature ParameterValueExample
locationyes/nolocation=no
menubaryes/nomenubar=no
minimizableyes/nominimizable=no
modalyes/nomodal=yes
personalbaryes/nopersonalbar=yes/true
resizableyes/noresizable=no
scrollbarsyes/noscrollbars=no
statusyes/nostatus=no
titlebaryes/notitlebar=yes

Features

Feature ParameterValueExample
toolbaryes/notoolbar=yes
toppixel valuetop=20
heightpixel valueheight=200
widthpixel valuewidth=200
innerHeightpixel valueinnerHeight=200
innerWidthpixel valueinnerWidth=200
outerHeightpixel valueouterHeight=200
outerWidthpixel valueouterWidth=200
leftpixel valueleft=20

close ( ) Method

Once a window is open, the close ( ) method is used to close it. It closes the current window or the window on which it was called. This method is only allowed to be called for windows that were opened by a script using the window.open() method. It is often used together with open ( ) method.

Syntax: – window.close ( )

Tagged : / / / /