Unit 2 Notes
Unit 2 Notes
Unit 2 Notes
This example uses the method to "find" an HTML element (with id="demo") and changes the
element content (innerHTML) to "Hello JavaScript":
Example
<!DOCTYPE html>
<html>
<head>
<script>
function myFunction() {
document.getElementById("demo").innerHTML = "Paragraph changed.";
}
</script>
</head>
<body>
</body>
</html>
Example
document.getElementById("demo").style.display = "none";
Example
document.getElementById("demo").style.display = "block";
JavaScript Where To
The <script> Tag
In HTML, JavaScript code must be inserted between <script> and </script> tags.
JavaScript in <head> or <body>
External JavaScript
External scripts are practical when the same code is used in many different web pages.
To use an external script, put the name of the script file in the src (source) attribute of
a <script> tag:
Example
<script src="myScript.js"></script>
"The W3C Document Object Model (DOM) is a platform and language-neutral interface that
allows programs and scripts to dynamically access and update the content, structure, and style
of a document."
In other words: The HTML DOM is a standard for how to get, change, add, or delete HTML
elements.
When a web page is loaded, the browser creates a Document Object Model of the page.
HTML DOM properties are values (of HTML Elements) that you can set or change.
If you want to access any element in an HTML page, you always start with accessing the
document object.
Below are some examples of how you can use the document object to access and manipulate
HTML.
Property Description
Method Description
Method Description
<div id="myDIV">
<span id="mySpan1" style="font-size:35px;">A Span element 1</span>
<span id="mySpan2" style="font-size:35px;">A Span element 2</span>
</div>
<script>
var c = document.getElementById("mySpan1");
function removeEle() {
c.parentNode.removeChild(c);
}
function appendEle() {
var d = document.getElementsByTagName("DIV")[0]
d.appendChild(c);
}
</script>
</body>
</html>
Creating and Replacing Element using Java Script
<!DOCTYPE html>
<html>
<body>
<div id = "div1">
This is first paragraph
</div>
<button onclick="replace()">create</button>
<script>
function replace() {
var ce = document.createElement("p");
ce.setAttribute("id", "p1");
ce.innerHTML = "New Paragraph Content";
var p = document.getElementsByTagName("div")[1].childNodes[0];
document.getElementsByTagName("div")[1].replaceChild(ce, p);
// document.getElementById("p1").innerHTML = "New Paragraph Content";
}
</script>
</body>
</html>
Adding Events Handlers
Method Description
document.getElementById(id).style.property = new style
Example
<html>
<body>
<p id="p2">Hello World!</p>
<script>
document.getElementById("p2").style.color = "blue";
</script>
</body>
</html>
RegExp Object
Example explained:
Modifiers
Modifier Description
g Perform a global match (find all matches rather than stopping after the first matc
Brackets
Expression Description
[abc] Find any character between the brackets
[^0-9] Find any character NOT between the brackets (any non-digit)
Metacharacters
Metacharacter Description
\d Find a digit
\D Find a non-digit character
\b Find a match at the beginning/end of a word, beginning like this: \bHI, end like th
Quantifiers
Quantifier Description
Exception Handling
The finally statement lets you execute code, after try and catch, regardless of the result.
Errors can be coding errors made by the programmer, errors due to wrong input, and other
unforeseeable things.
Example
function myFunction() {
var message, x;
message = document.getElementById("p01");
message.innerHTML = "";
x = document.getElementById("demo").value;
try {
if(x == "") throw "is empty";
if(isNaN(x)) throw "is not a number";
x = Number(x);
if(x > 10) throw "is too high";
if(x < 5) throw "is too low";
}
catch(err) {
message.innerHTML = "Error: " + err + ".";
}
finally {
document.getElementById("demo").value = "";
}
}
If a form field (fname) is empty, this function alerts a message, and returns false, to prevent the
form from being submitted:
<!DOCTYPE html>
<html>
<head>
<script>
function validateForm() {
var x = document.forms["myForm"]["fname"].value;
if (x == "") {
alert("Name must be filled out");
return false;
}
}
</script>
</head>
<body>
<form name="myForm" action="/action_page.php" onsubmit="return validateForm()"
method="post">
Name: <input type="text" name="fname">
<input type="submit" value="Submit">
</form>
</body>
</html>
<input id="numb">
<p id="demo"></p>
<script>
function myFunction() {
var x, text;
// Get the value of the input field with id="numb"
x = document.getElementById("numb").value;
</body>
</html>
If a form field (fname) is empty, the required attribute prevents this form from being submitted:
<!DOCTYPE html>
<html>
<body>
</body>
</html>
Built-in Objects
Built-in objects are not related to any Window or DOM object model.
These objects are used for simple data processing in the JavaScript.
1. Math Object
PI Returns Π value.
Methods Description
<html>
<head>
<title>JavaScript Math Object Methods</title>
</head>
<body>
<script type="text/javascript">
var value = Math.abs(20);
document.write("ABS Test Value : " + value +"<br>");
var value = Math.acos(-1);
document.write("ACOS Test Value : " + value +"<br>");
var value = Math.asin(1);
document.write("ASIN Test Value : " + value +"<br>");
var value = Math.atan(.5);
document.write("ATAN Test Value : " + value +"<br>");
</script>
</body>
</html>
Output
<html>
<head>
<title>JavaScript Math Object Properties</title>
</head>
<body>
<script type="text/javascript">
var value1 = Math.E
document.write("E Value is :" + value1 + "<br>");
var value2 = Math.LN2
document.write("LN2 Value is :" + value2 + "<br>");
var value3 = Math.LN10
document.write("LN10 Value is :" + value3 + "<br>");
var value4 = Math.PI
document.write("PI Value is :" + value4 + "<br>");
</script>
</body>
</html>
Output:
E Value is :2.718281828459045
LN2 Value is :0.6931471805599453
LN10 Value is :2.302585092994046
PI Value is :3.141592653589793
2. Date Object
Example:
var current_date = new Date();
Date Methods
Methods Description
getTimezoneOffset() Returns the timezone offset in minutes for the current locale.
setTime() Sets the number of milliseconds since January 1, 1970 at 12:00 AM.
<html>
<body>
<center>
<h2>Date Methods</h2>
<script type="text/javascript">
var d = new Date();
document.write("<b>Locale String:</b> " + d.toLocaleString()+"<br>");
document.write("<b>Hours:</b> " + d.getHours()+"<br>");
document.write("<b>Day:</b> " + d.getDay()+"<br>");
document.write("<b>Month:</b> " + d.getMonth()+"<br>");
document.write("<b>FullYear:</b> " + d.getFullYear()+"<br>");
document.write("<b>Minutes:</b> " + d.getMinutes()+"<br>");
</script>
</center>
</body>
</html>
Output:
3. String Object
Example:
var s = new String(string);
String Properties
Properties Description
constructor It returns the reference to the String function that created the object.
String Methods
Methods Description
charCodeAt() It returns the ASCII code of the character at the specified position.
concat() It combines the text of two strings and returns a new string.
split() It splits a string object into an array of strings by separating the string into the
substrings.
<html>
<body>
<center>
<script type="text/javascript">
var str = "CareerRide Info";
var s = str.split();
document.write("<b>Char At:</b> " + str.charAt(1)+"<br>");
document.write("<b>CharCode At:</b> " + str.charCodeAt(2)+"<br>");
document.write("<b>Index of:</b> " + str.indexOf("ide")+"<br>");
document.write("<b>Lower Case:</b> " + str.toLowerCase()+"<br>");
document.write("<b>Upper Case:</b> " + str.toUpperCase()+"<br>");
</script>
<center>
</body>
</html>
Output:
Functions Description
isNan() Returns true, if the object is Not a Number.
Returns false, if the object is a number.
parseFloat If the string begins with a number, the function reads through the string until it finds
(string) the end of the number; cuts off the remainder of the string and returns the result.
If the string does not begin with a number, the function returns NaN.
parseInt (string) If the string begins with an integer, the function reads through the string until it
finds the end of the integer, cuts off the remainder of the string and returns the
result.
If the string does not begin with an integer, the function returns NaN (Not a
Number).
String (object) Converts the object into a string.
eval() Returns the result of evaluating an arithmetic expression.
JavaScript Events
HTML Events
An HTML event can be something the browser does, or something a user does.
HTML allows event handler attributes, with JavaScript code, to be added to HTML elements.
<element event='some JavaScript'>
Example
<button onclick="document.getElementById('demo').innerHTML = Date()">The time is?
</button>
In the example above, the JavaScript code changes the content of the element with id="demo".
In the next example, the code changes the content of its own element (using this.innerHTML):
Example
<button onclick="this.innerHTML = Date()">The time is?</button>
JavaScript code is often several lines long. It is more common to see event attributes calling
functions:
Example
<button onclick="displayDate()">The time is?</button>
Common HTML Events
Event Description
onchange The attribute will work with elements like text box and select box.
DHTML JavaScript
DHTML stands for Dynamic HTML. Dynamic means that the content of the web page can be
customized or changed according to user inputs i.e. a page that is interactive with the user.
To integrate JavaScript into HTML, a Document Object Model(DOM) is made for the HTML
document. In DOM, the document is represented as nodes and objects which are accessed by
different languages like JavaScript to manipulate the document.
<html>
<head>
<title>DOM programming</title>
</head>
<body>
<h1>GeeksforGeeks</h1>
<p id = "geeks">Hello Geeks!</p>
<script style = "text/javascript">
document.getElementById("geeks").innerHTML =
"A computer science portal for geeks";
</script>
</body>
</html>
Output:
JSON - Introduction
JSON: JavaScript Object Notation.
Exchanging Data
When exchanging data between a browser and a server, the data can only be text.
JSON is text, and we can convert any JavaScript object into JSON, and send JSON to the server.
We can also convert any JSON received from the server into JavaScript objects.
This way we can work with the data as JavaScript objects, with no complicated parsing and
translations.
Sending Data
If you have data stored in a JavaScript object, you can convert the object into JSON, and send it
to a server:
Example
var myObj = {name: "John", age: 31, city: "New York"};
var myJSON = JSON.stringify(myObj);
window.location = "demo_json.php?x=" + myJSON;
Receiving Data
If you receive data in JSON format, you can convert it into a JavaScript object:
Example
var myObj = JSON.parse(myJSON);
document.getElementById("demo").innerHTML = myObj.name;
Storing Data
When storing data, the data has to be a certain format, and regardless of where you choose to
store it, text is always one of the legal formats.
Example
// Storing data:
myObj = {name: "John", age: 31, city: "New York"};
myJSON = JSON.stringify(myObj);
localStorage.setItem("testJSON", myJSON);
// Retrieving data:
text = localStorage.getItem("testJSON");
obj = JSON.parse(text);
document.getElementById("demo").innerHTML = obj.name;
Function Files & Http Request
A common use of JSON is to read data from a web server, and display the data in a web page.
<!DOCTYPE html>
<html>
<body>
<div id="id01"></div>
<script>
var xmlhttp = new XMLHttpRequest();
var url = "myTutorials.txt";
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var myArr = JSON.parse(this.responseText);
myFunction(myArr);
}
};
xmlhttp.open("GET", url, true);
xmlhttp.send();
function myFunction(arr) {
var out = "";
var i;
for(i = 0; i < arr.length; i++) {
out += arr[i].display + "</br>";
}
document.getElementById("id01").innerHTML = out;
}
</script>
</body>
</html>
Output
HTML Tutorial
CSS Tutorial
JavaScript Tutorial
jQuery Tutorial
SQL Tutorial
PHP Tutorial
XML Tutorial
JSON SQL
Customers.html
<!DOCTYPE html>
<html>
<body>
<h1>Customers</h1>
<div id="id01"></div>
<script>
var xmlhttp = new XMLHttpRequest();
var url = "https://www.w3schools.com/js/customers_mysql.php";
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
myFunction(this.responseText);
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
function myFunction(response) {
var arr = JSON.parse(response);
var i;
var out = "<table>";
</body>
</html>
<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
$outp = "[";
while($rs = $result->fetch_array(MYSQLI_ASSOC)) {
if ($outp != "[") {$outp .= ",";}
$outp .= '{"Name":"' . $rs["CompanyName"] . '",';
$outp .= '"City":"' . $rs["City"] . '",';
$outp .= '"Country":"'. $rs["Country"] . '"}';
}
$outp .="]";
$conn->close();
echo($outp);
?>