0% found this document useful (0 votes)
3 views

JavaScript- KT Document

Uploaded by

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

JavaScript- KT Document

Uploaded by

Singam Vinay
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 35

JavaScript:

• JS is a scripting language which is lightweight and is a tool for developers to add


interactivity to websites.
• JavaScript is inserted directly in the HTML of a page.
• It is used to create client-side dynamic pages and used to make webpages interactive and
is also compatible with other languages.
JavaScript Features:

• JavaScript is very easy to implement. All you need to do is put your code in the HTML
document and tell the browser that it is JavaScript.
• There are almost no limits to the things you can do with JavaScript on a web page like:
➢ Show or hide more information with the click of a button
➢ Change the color of a button when the mouse hovers over it
➢ Zooming in and out on an image
➢ Using dropdowns, enabling, and disabling it based on conditions.
• JavaScript can also be used to create browser games.
• Loading new content or data onto the page without reloading the page
• Validating input from Web forms
• JavaScript is relatively simple to learn .

How JavaScript works?


JavaScript is not understandable by computer, but only browser understands JavaScript. So, we
need a program to convert our JavaScript program into computer-understandable language. A
JavaScript engine is a computer program that executes JavaScript code and converts it into
computer understandable language.
JS Engine

Parsers in JS:

It checks for syntax. Parsing means analyzing and converting a program into an internal format
that a runtime environment can actually run, for example the JavaScript engine inside browsers.
In Parsing phase, code is broken down into tokens and the syntax parser converts these tokens
into abstract syntax tree(AST). AST is used by bytecode generator to form byte code which in turn
is used by the interpreter to run the code.
Interpreter lets the lets the AST to get converted into Byte code. In V8 engine, this process is
known as Ignition. The compiler Turbofan is used in v8. JavaScript Engine’s speed gets improved
since profiler and compiler will be producing and updating the optimized byte code.Tools that can
be used to generate the code for a parser are called parser generators or compiler.
E.g., 437 + 347

A lexer and a parser work in sequence: the lexer scans the input and produces the matching tokens,
the parser scans the tokens and produces the parsing result. A grammar is a list of rules that define
how each construct can be composed. For example, a rule for an if statement could specify that it
must starts with the “if” keyword, followed by a left parenthesis, an expression, a right parenthesis,
and a statement. In CFG(context free grammar), the start symbol is used to derive the string. You
can derive the string by repeatedly replacing a non-terminal by the righthand side of the production,
until all non-terminals have been replaced by terminal symbols.
Top-down parser: When the parser starts constructing the parse tree from the start symbol and
then tries to transform the start symbol to the input, it is called top-down parsing. It builds parse
trees from top(root) to bottom(leaves).It follows left most derivation.
E.g., Input String: abbcde

Consider the grammar,

Bottom-up parser: It will start from string and proceed to start. It builds the parse trees from
leaves and work up to the root. It will follow rightmost derivation in reverse order.
E.g.,

Execution Context:
Whenever the JavaScript engine receives a script file, it first creates a default Execution Context
known as the Global Execution Context (GEC). JavaScript code is executed inside execution
context. It has two components in it: Memory(stores variables and functions) and code(code is
executed). Memory component is also known as variable environment. Code is also known as
Thread of execution.
E.g., Phase I(Memory)

Phase II(Execution)
Call Stack/Execution Stack – A stack data structure in which new execution context is created,
itis pushed on top of Global Execution context. The execution context is managed by call stack.
When the execution is completed it is popped off from the stack.
push

Exec 1 Exec 2

GEC GEC pop GEC

Script Tag:

• The script tag specifies JavaScript is being used.


• The script tag can be placed in <head> or <body> section of an HTML Page. It can also
be placed in an external JavaScript file.
<html>
<head>
<script type="text/javascript">
function msg(){
alert("This is an alert box");
}
</script>
</head>
</html>
• Linking to an external JavaScript file:
<script src="filename" type="text/javascript"></script>

Variables:
Variables in JavaScript are declared using ‘var’, ‘let’, ‘const’ keyword.
Syntax: var name = expression;
Rules while declaring variables:
1. Name must start with a letter, underscore (_), or dollar ($) sign.
2. After first letter we can use digits (0 to 9), for example value1.
3. JavaScript variables are case sensitive.
var let const
• The scope of • The scope of • The scope is block
the var keyword is the a let variable is only scope.
global or function block scoped. It can’t • When users declare
scope. be accessible outside a const variable, they
• It can be declared the particular block need to initialize it,
without initialization • It can be declared otherwise, it returns
without initialization an error.

• variables defined • The code returns an • constant declared


outside the function error because we are inside a block will not
can be accessed accessing accessible outside of
globally, and variables the let variable outside that block.
defined inside a the function block.
particular function can
be accessed within the E.g, <script> E.g, <script>
function. let a = 10; {
E.g, <script> function f() { //inside block
var b=20; if (true) { const Pi = 3.14;
function f() { let b = 9 alert(Pi);
var a = 10; console.log(b); }
console.log(a) //prints 9 // outside block
} } alert(Pi); // error
f(); //prints 10 console.log(b); // gives error </script>
(ReferenceError: b is not
// ‘a’ cannot be accessible defined)
outside of function } f()
console.log(a);
console.log(a); // prints 10
console.log(b);// 20
</script>
</script>

• User can re-declare • Users cannot re-declare • It cannot be updated


variable using var and the variable defined or re-declared
user can update var with the let keyword but E.g, <script>
variable. can update it. const a = 10;
function f() {
E.g, <script> E.g, <script> a=9
var a = 10; let a = 10 console.log(a);
//re-declare is allowed // re-declare is not allowed //displays error
var a = 8; let a = 10 }
a = 7; // It is allowed f();
console.log(a);// prints 7 a = 10 </script>
</script> </script>
Data types, Operators:
• Datatypes is used to hold different types of values. JavaScript provides datatypes such
as:
1. Number - represents numeric values
2. Boolean - represents Boolean values either true or false
3. String - represents sequence of characters
4. Array - represents group of similar values
5. Object - represents an instance through which we can access members
6. Null - represent no value, i.e., variable assigned an empty or null value
7. Undefined - represents an undefined value
• The typeof operator returns the type of a variable .
• Operators include:
Arithmetic Operators(+, -,*,%,/,++,--)
Comparison (Relational) Operators(==,===,>,>=,<,<=,!=)
Logical Operators(&&,||,!)
Bitwise Operators(&,|,^,<<,>>,~)
Assignment Operators(=,+=,*=,-=,/=,%=)
Number:
The JavaScript Number is used to represent a numerical value. Number object can be created using
Number() constructor. It may be integer or floating-point.
Syntax: var n=new Number(value);
E.g, var num=new Number(20);
var x=52.4;
var y=12e3;//12000
The Number constants include:
MIN_VALUE, MAX_VALUE, NaN, POSITIVE_INFINITY, NEGATIVE_INFINITY

Arrays:
Syntax:
1. Declaring an empty array:
var name = []; E.g., const cars = [];
2. Initialize an array with prefilled values:
var name = [value, value, ..., value];
E.g.: const cars = ["Saab", "Volvo", "BMW"];
3. Storing the element by specifying index value:
name[index] = value; // store element
E.g. const cars = [];
cars [0] = “Saab”;
cars [1] = “Volvo”;
cars [2] = “BMW”;

4. Arrays can be declared using new Keyword:


var arrayname=new Array ();
E.g. var cars = new Array ();
cars [0] = "Saab";
cars [1] = "Volvo";
cars [2] = "BMW";

5. Arrays can be initialize through constructor also:


E.g. var cars=new Array("Saab","Volvo","BMW");

• Array Methods:
concat, join, pop, push, reverse, shift, slice, sort, splice, toString, unshift
E.g. var a = ["Stef", "Jason", “Reena”]; // Stef, Jason, Reena
a. push("Brian"); // Stef, Jason, Reena, Brian
a.unshift("Kelly"); // Kelly, Stef, Jason, Reena, Brian
a.pop(); // Kelly, Stef, Jason, Reena
a.shift(); // Stef, Jason, Reena
a.sort(); // Jason, Reena, Stef
push and pop add / remove from back
unshift and shift add / remove from front
Map, Reduce, Filter:
• Map, reduce, and filter are all array methods in JavaScript. Each one will iterate over an
array and perform a transformation or computation. Each will return a new array based on
the result of the function.
• map() method: The map() method is used for creating a new array from an existing one,
applying a function to each one of the elements of the first array.
E.g., const numbers = [1, 2, 3, 4];
const doubled = numbers.map(item => item * 2);
console.log(doubled); // [2, 4, 6, 8]
• filter() method: The filter() method takes each element in an array and it applies a
conditional statement against it. If this conditional returns true, the element gets pushed
to the output array. If the condition returns false, the element does not get pushed to the
output array.
E.g., const numbers = [1, 2, 3, 4];
evens = numbers.filter(item => item % 2 === 0); [filter]
console.log(evens); // [2, 4]
• reduce() method: The reduce() method reduces an array of values down to just one value.
To get the output value, it runs a reducer function on each element of the array.
Syntax: arr.reduce(callback[, initialValue])
• The callback argument is a function that will be called once for every item in the
array. This function takes four arguments, but often only the first two are used.
1. accumulator - the returned value of the previous iteration
2. currentValue - the current item in the array
3. index - the index of the current item
4. array - the original array on which reduce was called.

• The initialValue argument is optional. If provided, it will be used as the initial


accumulator value in the first call to the callback function.
E.g., Adding every number together in array of numbers

const numbers = [1, 2, 3, 4];


const sum = numbers.reduce(function (result, item) {
return result + item;
}, 0);
console.log(sum); // 10
Strings:
• String is an object that represents a sequence of characters.
1. Declaring through String Literal:
var s = "Hello John!";
2. Declaring through new keyword:
var str=new String("hello John!");
• Some of the JavaScript String Methods include: charAt(), charCodeAt(), concat(),
indexOf(), lastIndexOf(), replace(), substr(), substring(), toLowerCase(), toUpperCase(),
slice(), split(), trim(), toString() etc.,
E.g. var s = "Connie Client";
var fName = s.substring(0, s.indexOf(" ")); // "Connie"
var len = s.length; // 13
var letter=s.charAt(2);// n
//split, reverse, join:
var str = "the quick brown fox";
var a = str.split(" "); // ["the", "quick", "brown", "fox"]
a.reverse(); // ["fox", "brown", "quick", "the"]
str= a.join("!"); // "fox!brown!quick!the"
Object:
• Object is an entity having state and behavior (properties and method). objects can contain
many values. The values are written as name:value pairs.
• Syntax: object={property1:value1,
property2:value2,….
propertyN:valueN}
• object properties can be accessed as: objectName.propertyName
E.g., const person = {
firstName: "Rita",
lastName: “Khan”};

person.firstname; //Rita
Dates:
• The JavaScript date object can be used to get year, month, and day.
Syntax:
var date = new Date();
• Some of the methods include : getDate(), getHours(), getMilliseconds(), getMonth(),
getSeconds(), setDate(), setDay(), setHours() etc.
var date=new Date();
document.write("<br>Current date is :"+date );
document.write("<br>Month :"+(date.getMonth() + 1));
document.write("<br>Year :"+date.getFullYear());
document.write("<br>Date :"+ date.getDate());

Math:
• The JavaScript math object provides several constants and methods to perform
mathematical operation.
• Some of the Methods are abs(), ceil(), cos(), floor(), log(), max(), min(), pow(), random(),
round(), sin(), sqrt(), tan()

E.g., Math.round(4.6); // 5 [ returns the nearest integer]


Math.ceil(4.9); // 5 [returns the value rounded up to its nearest integer]
Math.floor(4.9); // 4 [returns the value rounded down to its nearest integer]
Math.pow(8, 2);// 64[returns the value of 8 to the power of 2]
Functions:
It is used to perform operations. It makes program compact. Don’t need to write many lines of
code each time to perform a common task.
Syntax: function functionName([arg1, arg2, ...argN]){
//statements;
}
E.g., function myFunction() {
alert("Hello!");
alert("How are you?");}
call() method: The call() method is used to bind the value to the function and execute the
function.
E.g.,

Output:

apply() method:
apply() method is similar to call() method. The apply() method takes arguments as an array.

Output:

bind():
The bind() method sets the values to the function, but the function needs to be invoked
seperately.
Output:

Arrow Function: Arrow functions allow us to write shorter function syntax


E.g; var myFunction = (a, b) => a * b;
myFunction(4,5) //output:20
In normal form,
Var myFunction = function(a,b){
return a*b;
}
Closure:
Closure means that an inner function always has access to the variables and parameters of its
outer function.
E.g., const add = (function () {
var counter = 0;
return function () {
counter += 1;
return counter}
})();

add();//counter=1
add();//counter=2
add();// counter=3
eval():
The eval() function in JavaScript is used to evaluate the expression.

setTimeout(): The setTimeout() method in JavaScript is used to execute a function after waiting
for the specified time interval. Unlike the setInteval() method, the setTimeout() method executes
the function only once. The clearTimeout() method can be used to stop the timeout
E.g., var a;
a = setTimeout(fun, 2000);
function fun() {
alert(" This will be displayed after 2 sec!");
}
setInterval():The setInterval() method in JavaScript is used to repeat a specified function at every
given time-interval. It evaluates an expression or calls a function at given intervals. The
clearInterval() is used to stop the function being called. It will be executed multiple times.
E.g., var a;
a = setInterval(fun, 3000);
function fun() {
alert("The alert box will be displayed for every 3seconds");
}

JS Errors:
There are different types of error such as:
• EvalError – If an error occur during eval() function
• RangeError- If an out of range occurs
• ReferenceError- If an illegal reference occurs
• SyntaxError- If a syntax error occurs
• TypeError- If a type error occurs
An exception is a condition that disrupts the normal flow of execution. Exception handling is a
process or method used for handling the abnormal statements in the code and executing them.
Try catch:
• The try statement is used to execute a block of a code, and the catch block is used to handle
the error.
• The finally statement defines a block of code which has to be run regardless of exception
occurs or not.
• The throw statement is used to define custom error
throw syntax: try {
throw new Error(“This is a user defined statement!”);
} catch (e) {
document.write(e.message);
}

Output:

JS RegEx: A regular expression is a pattern of characters. In JavaScript, a Regular Expression


(RegEx) is an object that describes a sequence of characters used for defining a search pattern.
Regex is used for pattern-matching. RegEx methodes include test(), match(), matchAll(), exec(),
search() etc.,
E.g.,

JS Collections
• Set: It stores a collection of unique values of any type.
Syntax: let setObject = new Set();
const letters = new Set(["a","b","c"]);
• size of set: To get the number of elements that the set holds, you use the size property of
the Set object.
let size = letters.size;
console.log(size); // 3
• To add an element to the set, add() method is used.
Adding an element:
let chars = new Set(['a', 'a', 'b', 'c', 'c']);
console.log(chars); // {a,b,c} [prints only unique elements]
chars.add('d');
console.log(chars); // {a,b,c,d}
• add() method is chainable, you can add multiple items to a set using a chain statement:
chars.add('e')
.add('f');
console.log(chars); //{a,b,c,d,e,f}
Check if value exists: The has() method returns true if the set contains the element, otherwise, it
returns false.
let exist = chars.has('b');
console.log(exist); // true
Remove an element: The delete() method is used to delete specified element from the set.
chars.delete('c');
console.log(chars); // {"a", "b", "d", "e"}
Iterating elements in set: The JavaScript Set entries() method returns an object of new set
iterator. This object contains an array of [value, value] for each element. It maintains an insertion
order. To keep the values unique it uses the key internally. Set considers the value of element as a
key. In array[value, value], the first value represents the key whereas the second value represents
the value of element.
<script>
var set = new Set();
set.add("jQuery");
set.add("AngularJS");
set.add("Bootstrap");
var itr=set.entries(); Output:

for(i=0;i<set.size;i++)
{
document.writeln(itr.next().value+"<br>");
}
</script>
forEach: The JavaScript Set forEach() method executes the specified function once for each value in the
Set object.

<script>
var set = new Set(["jQuery","AngularJS","Bootstrap"]);
document.writeln("Fetching values :"+"<br>"); Output:
set.forEach(function display(value1,value2,set)
{
document.writeln('key[' + value1 + '] = ' + value2+"<br>");
})
</script>

Weak Set:
The JavaScript WeakSet object is the type of collection that allows us to store weakly held objects.
WeakSet may be automatically garbage-collected.
let computer = {type: 'laptop'};
let server = {type: 'server'};
let equipment = new WeakSet([computer, server]);
if (equipment.has(server)) {
console.log('We have a server');
}
Output: We have a server
Map:
The JavaScript Map object is used to map keys to values. It stores each element as key-value pair.
It operates the elements such as search, update and delete on the basis of specified key.
Syntax: let map = new Map([iterable]);
iterable - It represents an array and other iterable object whose elements are in the form of key-
value pair

Passing an itearable object: An iterable object to the Map() constructor can also be passed:
var map = new Map([
[1, 'jQuery'],
[2, 'AngularJS'],
[3, 'BootStrap']
]);
Adding Elements: The JavaScript map set() method is used to add or updates an element to map
object with the particular key-value pair. Each value must have a unique key.
E.g., var map=new Map();
map.set(1,"jQuery");
map.set(2,"AngularJS");
map.set(3,"Bootstrap");
set() method is chainable, so multiple elements can be inserted to map using chain statement:
map.set(4, 'Java')
.set(5, ‘.Net’);
Accessing elements: The JavaScript map get() method returns the value of specified key of an
element from a Map object. If you pass a key that does not exist, the get() method will
return undefined.
Syntax:mapObj.get(key);
map.get(1); // jQuery
map.get(3); //BootStrap
map.get(4); //.Net
Check if value exists: To check if a key exists in the map, you use the has() method.
map.has(“Java”); //true
map.has(“sql”); //false

Deleting elements: The JavaScript map delete() method is used to remove all the elements
from Map object.
Syntax: mapObj.delete()
map.delete(2);
Iterating Elements:
entries()- The JavaScript map entries() method returns an object of new map iterator. This object
contains the key-value pair for each element. It maintains insertion order.
Syntax: mapObj.entries()
<script>
var map=new Map();
map.set(1,"jQuery");
map.set(2,"AngularJS"); Output:
map.set(3,"Bootstrap");
var itr=map.entries();
document.writeln(itr.next().value+"<br>");
document.writeln(itr.next().value+"<br>");
document.writeln(itr.next().value);
</script>
values()- The JavaScript map values() method returns an object of new Map iterator. This object
contains the value for each element. It maintains insertion order.
E.g., <script>
var map=new Map(); Output:
map.set(1,"jQuery");
map.set(2,"AngularJS");
map.set(3,"Bootstrap");
var itr=map.values();
document.writeln(itr.next().value+"<br>");
document.writeln(itr.next().value+"<br>");
document.writeln(itr.next().value);
</script>

Weak Map: The JavaScript WeakMap object is a type of collection which is almost similar to
Map. It stores each element as a key-value pair where keys are weakly referenced. Here, the keys
are objects and the values are arbitrary values. In WeakMap, if there is no reference to a key object,
they are targeted to garbage collection.
Syntax: new WeakMap([iterable])
<script>
var wm = new WeakMap();
var obj1 = {};
var obj2 = {};
var obj3= {};
wm.set(obj1, "jQuery");
wm.set(obj2, "AngularJS"); Output:
wm.set(obj3,"Bootstrap");
document.writeln(wm.get(obj1)+"<br>");
document.writeln(wm.get(obj2)+"<br>");
document.writeln(wm.get(obj3));
</script>

Event-Driven Programming:

• Event- The change in the state of an object


• Event Handling- When javascript code is included in HTML, js react over these events and
allow the execution. This process of reacting over the events is called Event Handling.
JavaScript handles the HTML events via Event Handlers.
Event Listeners:
• The addEventListener() method is used to attach an event handler to a particular element.
Syntax: element.addEventListener(event, function)
• .The style of an HTML element can also be changed :
Syntax: element.style.property = new style
E.g., document.getElementById("firname").addEventListener("click",inputClick);
function inputClick(){
var h=document.getElementById("firname");
h.style.color="#C70039 ";
h.style.fontWeight="bold";
}
Some of the HTML events and their event handlers include:
Event Event Handler Description
click onclick When user clicks the mouse
mouseover onmouseover When the mouse moves over an element
mouseout onmouseout When the mouse leaves an element
mousedown onmousedown When the mouse button is pressed over an element
mouseup onmouseup When the mouse button is released over the element
focus onfocus When the user focuses on an element
submit onsubmit When the user submits the form
load onload When the user enters the page
unload onunload When the user leaves the page
resize onresize When the user resizes the window of the browser

Examples of events:

onload - The onload event occurs when an object has been loaded. The onload event can be used
to check the visitor's browser type and browser version information, and can also be used to deal
with cookies
onfocus - The onfocus event occurs when an element gets focus. It is often used with <input>,
<select>, <a>

onerror - The onerror event is triggered if an error occurs while loading an external file (e.g. a
document or an image).

BOM:
The Browser Object Model (BOM) is used to interact with the browser. The default object of
browser is window.
1.Window Object:
The window object represents a window in browser. Some of the methods include:
• alert() - displays the alert box containing message with ok button.
• confirm() - displays the confirm dialog box containing message with ok and cancel button.
• prompt() - displays a dialog box to get input from the user.
• open() - opens the new window.
• close() - closes the current window.
E.g. window.alert(“This is an window alert!”); confirm(“Are you sure you want to exit:”);

var n=window.prompt("Enter a number","");


window.alert("The cube a number is: "+n*n*n);

2. History Object:
The history object represents an array of URLs visited by the user. By using this object, one can
load previous page, forward or any particular page. It can be accessed by: window.history or
history

Methods of history object:


1.forward() - loads the next page.
2.back() - loads the previous page.
3.go() - loads the given page number.

history.back(); //for previous page


history.forward(); //for next page
history.go(2); //for next 2nd page
history.go(-2); //for previous 2nd page
3.Navigator Object:
The JavaScript navigator object is used for browser detection. It can be used to get browser
information such as appName, appCodeName, userAgent etc. Some of the properties of navigator
object include:
• appName - returns the name
• appVersion - returns the version
• appCodeName - returns the code name
• cookieEnabled - returns true if cookie is enabled otherwise false
E.g. document.write("<br><br>Navigator appName : "+navigator.appName);
document.write("<br><br>Navigator code Name : "+navigator.appCodeName);
document.write("<br><br>Navigator platform : "+navigator.platform);
document.write("<br><br>Navigator version : "+navigator.appVersion);
output:

4.Screen Object:
The JavaScript screen object holds information of browser screen. It can be used to display
screen width, height, colorDepth, pixelDepth etc. The properties of screen object include:
• width - returns the width of the screen
• height - returns the height of the screen
• availWidth - returns the available width
• availHeight - returns the available height
• colorDepth - returns the color depth
E.g. alert("Screen With :"+screen.width+"\n Screen Height :"+screen.height+
"\nScreen Color Depth:"+screen.colorDepth+
"\nWindow width :"+window.innerWidth);

5.Location Object:
The location object can be used to get the current page address (URL) and to redirect the browser
to a new page. The properties of the location object include:
• href - returns the href (URL) of the current page
• hostname - returns the domain name of the web host
• pathname - returns the path and filename of the current page
• protocol - returns the web protocol used (http: or https:)
• assign() - loads a new document

E.g. document.write("<br><br> href of the location : "+location.href);


document.write("<br><br> Host of the location : "+location.host);
document.write("<br><br> protocol of the location : "+location.protocol);
Output:

DOM:
When a web page is loaded, the browser creates a Document Object Model of the page. The
document object represents the whole html document. By the help of document object, JS gets
power to create dynamic HTML. The HTML DOM defines:

• The HTML elements as objects


• The properties of all HTML elements
• The methods to access all HTML elements
• The events for all HTML elements

The method of document object include:

• write("string")- writes the given string on the document


• writeln("string")- writes the given string in a newline on the document
• getElementById()- returns the element having the given id value.
• getElementsByName()- returns all the elements having the given name value.
• getElementsByTagName()- returns all the elements having the given tag name.
• getElementsByClassName()- returns all the elements having the given class name.
Accessing Elements:
1.document.getElementById():
• document.getElementById returns the DOM object for an element with a given id
• It can change the text inside most elements by setting the innerHTML property
• The innerHTML property is useful for getting or replacing the content of HTML elements.
• It can change the text in form controls by setting the value property
Example:
2.document.getElementsByClassName(): The getElementsByClassName() method returns a
collection of elements with a specified class name. The elements in a collection can be accessed
by index

Output:

3.document.getElementByTagName(): The document.getElementsByTagName() method returns


all the element of specified tag name.

Output:

HTML Objects:
Disabling a Button: The disabled property sets whether an input button should be disabled, or
not. A disabled element is unusable and un-clickable.
Syntax: buttonObject.disabled = true|false
AutoFocus a Button: The input button automatically gets focus when the page is loaded.
Disbaling a Radio Button:
The disabled property sets or returns whether a radio button should be disabled, or not. It returns
true if the radio button is disabled, otherwise it returns false.
Syntax: radioObject.disabled = true|false

Output:

DropDowns:
• A dropdown list is a toggleable menu that allows the user to choose one option from
multiple ones. When you click or choose this option, that function triggers and starts
performing.
• selectedIndex: The selectedIndex property sets or returns the index of the selected option
in a drop-down list. The index starts from 0.
• onchange - The onchange event occurs when the value of an element has been changed
You can also set the index value:
document.getElementById(“myList”).selectedIndex= “3”; //python

Disabling Radio button based on drop down selection:

Consider the below example:


CheckBox:
A checkbox is a selection box that allows the users to make the binary choice (true or false) by
checking and unchecking it. The checked property sets or returns whether a checkbox should be
disabled, or not. If a checkbox is marked or checked, it returns true. If a checkbox is unmarked or
not checked, it returns false. Checkbox allows multiple selections at once.
E.g., Displaying a message if checkbox is checked:
Basic Login and Registration form validation page using Events and Event Listeners:
Login .html:

Validation.js
click event:

LoginSuccess.html

Registration Form.html
Registration Form:

Registration Validation.JS
Name validation:

Mouseover event:
Password Validation:

Phone validation:

You might also like