Example 1
Working with numbers in JavaScript:
|
// create Infinity from numbers
document.write ("1 / 0 = ");
document.write (1 / 0); // output: Infinity
document.write ("<br />");
document.write ("-1 / 0 = ");
document.write (-1 / 0); // output: -Infinity
document.write ("<br />");
document.write ("0 / 0 = ");
document.write (0 / 0); // output: NaN
document.write ("<br />");
document.write ("2^1024 = ");
document.write (Math.pow (2, 1024)); // output: Infinity
document.write ("<br />");
document.write ("2^1023 = ");
document.write (Math.pow (2, 1023)); // output: 8.98846567431158e+307
document.write ("<br />");
// the real limit for integers
var num1 = Math.pow (2, 53) - 1;
var num2 = Math.pow (2, 53);
var num3 = Math.pow (2, 53) + 1;
document.write ("2^53 - (2^53 - 1) = ");
document.write (num2 -num1); // output: 1
document.write ("<br />");
document.write ("(2^53 + 1) - 2^53 = ");
document.write (num3 -num2); // output: 0
document.write ("<br />");
var num1 = -1 * Math.pow (2, 53) - 1;
var num2 = -1 * Math.pow (2, 53);
var num3 = -1 * Math.pow (2, 53) + 1;
document.write ("(-1 * 2^53) - (-1 * 2^53 - 1) = ");
document.write (num2 -num1); // output: 0
document.write ("<br />");
document.write ("(-1 * 2^53 + 1) - (-1 * 2^53) = ");
document.write (num3 -num2); // output: 1
document.write ("<br />");
// addition, subtraction operations for Infinity
document.write ("Infinity + 1 = ");
document.write (Infinity + 1); // output: Infinity
document.write ("<br />");
document.write ("Infinity - 1 = ");
document.write (Infinity - 1); // output: Infinity
document.write ("<br />");
document.write ("-Infinity + 1 = ");
document.write (-Infinity + 1); // output: -Infinity
document.write ("<br />");
document.write ("-Infinity - 1 = ");
document.write (-Infinity - 1); // output: -Infinity
document.write ("<br />");
document.write ("Infinity + Infinity = ");
document.write (Infinity + Infinity); // output: Infinity
document.write ("<br />");
document.write ("Infinity + -Infinity = ");
document.write (Infinity + -Infinity); // output: NaN
document.write ("<br />");
document.write ("Infinity - Infinity = ");
document.write (Infinity - Infinity); // output: NaN
document.write ("<br />");
document.write ("Infinity - -Infinity = ");
document.write (Infinity - -Infinity); // output: Infinity
document.write ("<br />");
// multiplication operations for Infinity
document.write ("Infinity * 1 = ");
document.write (Infinity * 1); // output: Infinity
document.write ("<br />");
document.write ("Infinity * -1 = ");
document.write (Infinity * -1); // output: -Infinity
document.write ("<br />");
document.write ("Infinity * 0 = ");
document.write (Infinity * 0); // output: NaN
document.write ("<br />");
document.write ("Infinity * Infinity = ");
document.write (Infinity * Infinity); // output: Infinity
document.write ("<br />");
document.write ("Infinity * -Infinity = ");
document.write (Infinity * -Infinity); // output: -Infinity
document.write ("<br />");
// division operations for Infinity
document.write ("Infinity / 1 = ");
document.write (Infinity / 1); // output: Infinity
document.write ("<br />");
document.write ("Infinity / -1 = ");
document.write (Infinity / -1); // output: -Infinity
document.write ("<br />");
document.write ("Infinity / 0 = ");
document.write (Infinity / 0); // output: Infinity
document.write ("<br />");
document.write ("Infinity / Infinity = ");
document.write (Infinity / Infinity); // output: NaN
document.write ("<br />");
document.write ("Infinity / -Infinity = ");
document.write (Infinity / -Infinity); // output: NaN
document.write ("<br />");
|
|
Did you find this example helpful?
yes
no
|
Example 2
How to check the undefined state of a variable:
|
// use the undefined global property for checking
if (x === undefined)
document.write ("x is undefined <br />");
else
document.write ("x is defined <br />");
// use the typeof operator for checking
if (typeof x == 'undefined')
document.write ("x is undefined <br />");
else
document.write ("x is defined <br />");
var x; // declare x without a value
// use the undefined global property for checking
if (x === undefined)
document.write ("x is undefined <br />");
else
document.write ("x is defined <br />");
// use the typeof operator for checking
if (typeof x == 'undefined')
document.write ("x is undefined <br />");
else
document.write ("x is defined <br />");
x = 2; // x has a value
// use the undefined global property for checking
if (x === undefined)
document.write ("x is undefined <br />");
else
document.write ("x is defined <br />");
// use the typeof operator for checking
if (typeof x == 'undefined')
document.write ("x is undefined <br />");
else
document.write ("x is defined <br />");
|
|
Did you find this example helpful?
yes
no
|
Example 3
|
parseInt ("1010", 2);
parseInt ("12", 8);
parseInt ("012");
parseInt ("10", 10);
parseInt ("10");
parseInt ("10.22");
parseInt ("A", 16);
parseInt ("0xA");
parseInt ("10ABC");
parseInt ("012ABC");
parseInt ("0xArt");
|
|
Did you find this example helpful?
yes
no
|
Example 4
If the second parameter ( radix) is not specified, the parseInt method automatically detects the base.
In some cases, it returns unexpected result (for details, see the parseInt method):
|
// hexadecimal
parseInt ("10"); // return 10
// octal
parseInt ("010"); // return 8
// octal, 8 is not a valid octal digit
parseInt ("08"); // return 0
// octal, 9 is not a valid octal digit
parseInt ("09"); // return 0
|
|
Did you find this example helpful?
yes
no
|
Example 5
This example uses the encodeURIComponent method to encode form data before submitting.
This example and the next one use AJAX to submit a form without reloading the page. The two examples are similar, but the first one uses synchronous while the second one uses asynchronous data transfer. In synchronous mode, the send method of the XMLHttpRequest object waits for a reply, so the user cannot interact with the browser until the response has completed. In asynchronous mode, the send method does not wait for a reply but instead returns immediately, so it allows you to perform other operations while a time-consuming task is being performed in the background.
|
Code |
|
ajax_form.js |
|
register.php |
|
|
<head>
<script type="text/javascript" src="ajax_form.js"></script>
<style>
.error {
display: none;
color: #a00000;
font-weight: bold;
}
</style>
<script type="text/javascript">
function HideAllErrorFields () {
for (var i = 1; i <= 4; i++) {
var field = document.getElementById ("error" + i);
field.style.display = "none";
}
}
function ShowErrorFields (idsStr) {
var ids = idsStr.split (",");
for (var i = 0; i < ids.length; i++) {
var field = document.getElementById ("error" + ids[i]);
if (field) {
field.style.display = "block";
}
}
}
function AjaxSend (form, url, method) {
// hide all error fields
HideAllErrorFields ();
// get message data
var data = GetMessageBody (form); // defined in ajax_form.js
// send the request
var httpRequest = CreateRequestObj (); // defined in ajax_form.js
// try..catch is required if working offline
try {
httpRequest.open (method, url, false); // synchron
httpRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
httpRequest.send (data);
}
catch (e) {
alert ("Cannot connect to the server!");
return;
}
// handle the response
if (IsRequestSuccessful (httpRequest)) { // defined in ajax_form.js
if (httpRequest.responseText === "ok") { // registration is successful
alert ("Thank you for registering");
/*
// if redirection is required
location.href = "/index.php";
*/
}
else { // some fields are invalid
ShowErrorFields (httpRequest.responseText);
}
}
else {
alert ("An error occurred while registering. Please try it again.");
}
}
</script>
</head>
<body>
This is a sample registration form.
The username must be between 2 and 20 characters, the password must be between 6 and 20 characters.
A user named Dottoro is already registered.
<br />
Try to register both valid and invalid values!
<br /><br />
<form onsubmit="AjaxSend (this, 'register.php', 'post'); return false;">
User Name: <input type="text" name="userName" />
<div class="error" id="error1">Must be between 2 and 20 characters.</div>
<div class="error" id="error2">A user already exists with the same name.</div>
<br /><br />
Password: <input type="password" name="password" />
<div class="error" id="error3">Must be between 6 and 20 characters.</div>
<br /><br />
Repeat Password: <input type="password" name="repassword" />
<div class="error" id="error4">Must be the same as the password.</div>
<br /><br />
<input type="submit" value="Register" />
</form>
</body>
function CreateRequestObj () {
// although IE supports the XMLHttpRequest object, but it does not work on local files.
var forceActiveX = (window.ActiveXObject && location.protocol === "file:");
if (window.XMLHttpRequest && !forceActiveX) {
return new XMLHttpRequest();
}
else {
try {
return new ActiveXObject("Microsoft.XMLHTTP");
} catch(e) {}
}
}
// create HTTP request body form form data
function GetMessageBody (form) {
var data = "";
for (var i = 0; i < form.elements.length; i++) {
var elem = form.elements[i];
if (elem.name) {
var nodeName = elem.nodeName.toLowerCase ();
var type = elem.type ? elem.type.toLowerCase () : "";
// if an input:checked or input:radio is not checked, skip it
if (nodeName === "input" && (type === "checkbox" || type === "radio")) {
if (!elem.checked) {
continue;
}
}
var param = "";
// select element is special, if no value is specified the text must be sent
if (nodeName === "select") {
for (var j = 0; j < elem.options.length; j++) {
var option = elem.options[j];
if (option.selected) {
var valueAttr = option.getAttributeNode ("value");
var value = (valueAttr && valueAttr.specified) ? option.value : option.text;
if (param != "") {
param += "&";
}
param += encodeURIComponent (elem.name) + "=" + encodeURIComponent (value);
}
}
}
else {
param = encodeURIComponent (elem.name) + "=" + encodeURIComponent (elem.value);
}
if (data != "") {
data += "&";
}
data += param;
}
}
return data;
}
// returns whether the HTTP request was successful
function IsRequestSuccessful (httpRequest) {
// IE: sometimes 1223 instead of 204
var success = (httpRequest.status == 0 ||
(httpRequest.status >= 200 && httpRequest.status < 300) ||
httpRequest.status == 304 || httpRequest.status == 1223);
return success;
}
<?php
define("ERR_INVALID_USERNAME", "1");
define("ERR_EXISTING_USERNAME", "2");
define("ERR_INVALID_PASSWORD", "3");
define("ERR_DIFFERENT_PASSWORDS", "4");
$errors = array ();
if (isset ($_POST["userName"])) {
$username = $_POST["userName"];
$len = strlen ($username);
if ($len < 2 || $len > 20) {
array_push ($errors, ERR_INVALID_USERNAME);
}
else {
// check the name of registered users
if (strcasecmp ($username, "Dottoro") == 0) {
array_push ($errors, ERR_EXISTING_USERNAME);
}
}
}
else {
array_push ($errors, ERR_INVALID_USERNAME);
}
if (isset ($_POST["password"])) {
$password = $_POST["password"];
$len = strlen ($password);
if ($len < 6 || $len > 20) {
array_push ($errors, ERR_INVALID_PASSWORD);
}
else {
if (!isset ($_POST["repassword"]) || strcmp ($password, $_POST["repassword"]) != 0) {
array_push ($errors, ERR_DIFFERENT_PASSWORDS);
}
}
}
else {
array_push ($errors, ERR_INVALID_PASSWORD);
}
$response = "";
if (sizeof ($errors) > 0) {
$response = implode (",", $errors);
}
else {
// some db operations, save username and password ...
$response = "ok";
}
echo ($response);
?>
|
|
Did you find this example helpful?
yes
no
|
Example 6
This example is similar to the previous one, but it uses asynchronous data transfer and displays blinking text while waiting for the server response (the register_delay.php script waits two seconds before responding).
|
Code |
|
ajax_form.js |
|
register_delay.php |
|
|
<head>
<script type="text/javascript" src="ajax_form.js"></script>
<style>
.error {
display: none;
color: #a00000;
font-weight: bold;
}
#progress {
visibility: hidden;
color: #00a000;
}
</style>
<script type="text/javascript">
function HideAllErrorFields () {
for (var i = 1; i <= 4; i++) {
var field = document.getElementById ("error" + i);
field.style.display = "none";
}
}
function ShowErrorFields (idsStr) {
var ids = idsStr.split (",");
for (var i = 0; i < ids.length; i++) {
var field = document.getElementById ("error" + ids[i]);
if (field) {
field.style.display = "block";
}
}
}
var registering = false;
function OnReadyStateChanged (httpRequest, form) {
if (httpRequest.readyState == 0 || httpRequest.readyState == 4) {
registering = false;
StopAnim ();
// prevent memory leaks
httpRequest.onreadystatechange = null;
if (IsRequestSuccessful (httpRequest)) { // defined in ajax_form.js
if (httpRequest.responseText === "ok") { // registration is successful
alert ("Thank you for registering");
/*
// if redirection is required
location.href = "/index.php";
*/
}
else { // some fields are invalid
ShowErrorFields (httpRequest.responseText);
}
}
else {
alert ("An error occurred while registering. Please try it again.");
}
}
}
function AjaxSend (form, url, method) {
// avoid resend data while registering
if (registering) {
return;
}
// hide all error fields
HideAllErrorFields ();
// get message data
var data = GetMessageBody (form); // defined in ajax_form.js
// send the request
var httpRequest = CreateRequestObj (); // defined in ajax_form.js
// try..catch is required if working offline
try {
httpRequest.open (method, url, true); // asynchron
httpRequest.onreadystatechange = function () {OnReadyStateChanged (httpRequest, form)};
httpRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
httpRequest.send (data);
}
catch (e) {
alert ("Cannot connect to the server!");
return;
}
registering = true;
StartAnim ();
}
// blinking text
var animTimerId = 0;
function StartAnim () {
var progress = document.getElementById ("progress");
progress.style.visibility = "visible";
animTimerId = setInterval (RegAnim, 100);
}
function RegAnim () {
var progress = document.getElementById ("progress");
progress.style.visibility = (progress.style.visibility == "visible") ? "hidden" : "visible";
}
function StopAnim () {
var progress = document.getElementById ("progress");
progress.style.visibility = "hidden";
clearInterval (animTimerId);
}
</script>
</head>
<body>
This is a sample registration form.
The username must be between 2 and 20 characters, the password must be between 6 and 20 characters.
A user named Dottoro is already registered.
<br />
Try to register both valid and invalid values!
<br /><br />
<form onsubmit="AjaxSend (this, 'register_delay.php', 'post'); return false;">
User Name: <input type="text" name="userName" />
<div class="error" id="error1">Must be between 2 and 20 characters.</div>
<div class="error" id="error2">A user already exists with the same name.</div>
<br /><br />
Password: <input type="password" name="password" />
<div class="error" id="error3">Must be between 6 and 20 characters.</div>
<br /><br />
Repeat Password: <input type="password" name="repassword" />
<div class="error" id="error4">Must be the same as the password.</div>
<br /><br />
<input type="submit" value="Register" />
<div id="progress">Registering</div>
</form>
</body>
function CreateRequestObj () {
// although IE supports the XMLHttpRequest object, but it does not work on local files.
var forceActiveX = (window.ActiveXObject && location.protocol === "file:");
if (window.XMLHttpRequest && !forceActiveX) {
return new XMLHttpRequest();
}
else {
try {
return new ActiveXObject("Microsoft.XMLHTTP");
} catch(e) {}
}
}
// create HTTP request body form form data
function GetMessageBody (form) {
var data = "";
for (var i = 0; i < form.elements.length; i++) {
var elem = form.elements[i];
if (elem.name) {
var nodeName = elem.nodeName.toLowerCase ();
var type = elem.type ? elem.type.toLowerCase () : "";
// if an input:checked or input:radio is not checked, skip it
if (nodeName === "input" && (type === "checkbox" || type === "radio")) {
if (!elem.checked) {
continue;
}
}
var param = "";
// select element is special, if no value is specified the text must be sent
if (nodeName === "select") {
for (var j = 0; j < elem.options.length; j++) {
var option = elem.options[j];
if (option.selected) {
var valueAttr = option.getAttributeNode ("value");
var value = (valueAttr && valueAttr.specified) ? option.value : option.text;
if (param != "") {
param += "&";
}
param += encodeURIComponent (elem.name) + "=" + encodeURIComponent (value);
}
}
}
else {
param = encodeURIComponent (elem.name) + "=" + encodeURIComponent (elem.value);
}
if (data != "") {
data += "&";
}
data += param;
}
}
return data;
}
// returns whether the HTTP request was successful
function IsRequestSuccessful (httpRequest) {
// IE: sometimes 1223 instead of 204
var success = (httpRequest.status == 0 ||
(httpRequest.status >= 200 && httpRequest.status < 300) ||
httpRequest.status == 304 || httpRequest.status == 1223);
return success;
}
<?php
define("ERR_INVALID_USERNAME", "1");
define("ERR_EXISTING_USERNAME", "2");
define("ERR_INVALID_PASSWORD", "3");
define("ERR_DIFFERENT_PASSWORDS", "4");
$errors = array ();
if (isset ($_POST["userName"])) {
$username = $_POST["userName"];
$len = strlen ($username);
if ($len < 2 || $len > 20) {
array_push ($errors, ERR_INVALID_USERNAME);
}
else {
// check the name of registered users
if (strcasecmp ($username, "Dottoro") == 0) {
array_push ($errors, ERR_EXISTING_USERNAME);
}
}
}
else {
array_push ($errors, ERR_INVALID_USERNAME);
}
if (isset ($_POST["password"])) {
$password = $_POST["password"];
$len = strlen ($password);
if ($len < 6 || $len > 20) {
array_push ($errors, ERR_INVALID_PASSWORD);
}
else {
if (!isset ($_POST["repassword"]) || strcmp ($password, $_POST["repassword"]) != 0) {
array_push ($errors, ERR_DIFFERENT_PASSWORDS);
}
}
}
else {
array_push ($errors, ERR_INVALID_PASSWORD);
}
$response = "";
if (sizeof ($errors) > 0) {
$response = implode (",", $errors);
}
else {
// some db operations, save username and password ...
$response = "ok";
}
// 2 secs delay
sleep (2);
echo ($response);
?>
|
|
Did you find this example helpful?
yes
no
|
Example 7
Example 7 and 8 show how to avoid the use of the eval method to improve performance.
|
var str0 = "text0";
var str1 = "text1";
var str2 = "text2";
function GetStr (i) {
return eval ("str" + i);
}
document.write (GetStr (0)); // text0
document.write (GetStr (2)); // text2
|
|
Did you find this example helpful?
yes
no
|
Example 8
Since global variables are members of the window object, the previous example can also be implemented like this:
|
var str0 = "text0";
var str1 = "text1";
var str2 = "text2";
function GetStr (i) {
return window["str" + i];
}
document.write (GetStr (0)); // text0
document.write (GetStr (2)); // text2
|
|
Did you find this example helpful?
yes
no
|
Example 9
In some cases, a code snippet needs to be evaluated at runtime.
For example, when the response of an AJAX request contains some source code that needs to be executed by the JavaScript interpreter.
In that case, we can use both the eval method and the Function object to solve the problem.
The prefered solution is to use the Function object, because it is much more faster than the eval method (see eval for details).
This example uses the eval method:
|
var response = "2+3";
var result = eval (response);
document.write (result); // 5
|
|
Did you find this example helpful?
yes
no
|
Example 10
This example uses the Function object to implement the same functionality as the previous example:
|
var response = "2+3";
var result = (new Function ("return " + response)) ();
document.write (result); // 5
|
|
Did you find this example helpful?
yes
no
|
|