Introduction

JavaScript is a scripting language that runs in web browsers. Web browsers have a JavaScript engine. But because engines are not the same, you should test your JavaScript code in various web browsers. Ecma International is in charge of standardizing JavaScript.

JavaScript Usages

  • Validation
  • Event handler
  • Dynamic menus
  • Changing CSS properties
  • Adding content

Validation

signUp.html is the subscription form page. This page should check that values entered by the user are are valid before sending the parameters to the server.

signUp.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>JavaScript Example</title>
<script type="text/javascript">
function check() {
  var form = document.getElementById("signUpForm");
  var id = form.id.value;
  id = trim(id);
  if (id.length == 0) {
    alert("Invalid ID");
    return false;
  }
  var pass = form.passwd.value;
  pass = trim(pass);
  if (pass.length == 0) {
    alert("Invalid Password");
    return false;
  }
  var name = form.name.value;
  name = trim(name);
  if (name.length == 0) {
    alert("Invalid Name");
    return false;
  }
  var email = form.email.value;
  var chk = emailCheck(email);
  if (chk == false) {
    alert("Invalid Email");
    return false;
  }
  var mobile = form.mobile.value;
  mobile = trim(mobile);
  if (mobile.length == 0) {
    alert("Invalid Mobile");
    return false;
  }
  chk = beAllowStr(mobile,"0123456789-");
  if (chk == false) {
    alert("Invalid Mobile");
    return false;
  }
	
  return true;
}

function trim(str) {
  for (var i = str.length - 1; i >= 0; i--) {
    if (str[i] == " ") {
      str = str.substring(0, i);
    } else {
      break;
    }
  }
  for (var i = 0; i < str.length; i++) {
    if (str[i] == " ") {
      str = str.substring(i+1, str.length);
    }	
  }
  return str;
}

function beAllowStr(str, allowStr) {
  for (var i = 0;i < str.length; i++) {
    var ch = str.charAt(i);
    if (allowStr.indexOf(ch) < 0) {
      return false;
    }
  }
  return true;
}

function emailCheck(email) {
  var allowStr = "1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz@.-_";
  if (beAllowStr(email, allowStr) == false) {
    return false;
  }
  var golbang = 0;
  var dot = 0;
  if (email.length < 5) {
    return false;
  }
  if (email.indexOf("@") == -1) {
    return false;
  }
  if (email.indexOf(".") == -1) {
    return false;
  }
  if (email.indexOf(" ") != -1) {
    return false;
  }
  for (var i = 0;i < email.length; i++) {
    if (email.charAt(i) == "@") {
      golbang++;
    }
    if (email.charAt(i) == ".") {
      dot++;
    }
  }
  if (golbang != 1 || dot > 3) {
    return false;
  }
  if (email.indexOf("@") > email.indexOf(".")) {
    return false;
  }
  if (email.indexOf("@") == 0  || email.indexOf(".") == email.length - 1) {
    return false;
  }
  return true;
}
</script>
</head>
<body>
<h1>Sign Up</h1>
<form id="signUpForm" action="signUp_proc.jsp" method="post" onsubmit="return check();">
ID: <input type="text" name="id" value="heist" /><br />
Password: <input type="password" name="passwd" value="1440" /><br />
Name: <input type="text" name="name" value="John Doe" /><br />
Email: <input type="text" name="email" /><br />
Mobile: <input type="text" name="mobile" /><br />
<input type="submit" value="Submit" />
<input type="reset" value="Reset" />
</form>
</body>
</html>

Run the example
The above code is old-fashioned. It is desirable to use regular expressions to check whether an email is valid.

Modify the emailCheck() and trim() functions to use regular expressions.

function emailCheck(email) { 
  var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
  return re.test(email);
}

function trim(str) {
  return str.replace(/(^\s*)|(\s*$)/gi, "");
}

Create a function to validate mobile numbers like below.

function mobileCheck(mobile) {
  var re = /\d+-\d+-\d+/;
  return re.test(mobile);
}

Create signUp2.html using the above three functions to validate user input values.

Run the example

SignUp.html and signUp2.html differ in mobile validation criteria. The check() function in signUp.html assess the string consisting of numbers and dashes as a valid mobile number. The mobileCheck() function in signUp2.html considers the format 'one or more numbers - one or more numbers - one or more numbers' as a valid mobile number.

Event handler

The code for this button is:

<input type="button" value="Button" onclick="alert('Click Button!');" />

When you click the button, the alert() function runs. You can place a user-defined function in place of alert(). That user-defined function is called an event handler.

Links, submit buttons, and reset buttons have default behavior for events. In other words, links, submit buttons and reset buttons work without JavaScript. But the other buttons do nothing without event handlers.

In the subscription example, We made the check() function works before performing the basic operation of the submit button by adding the onsubmit attribute to the form element like below:

<form .. onsubmit="return check();">

The check() function must return a boolean value. Returning true makes the form does the default behavior that sends parameters to the server. Returning false disables the form's default behavior, so nothing happens after the check() function terminates.

Dynamic menus

The dTree in the link below is an excellent example to understand JavaScript dynamic menus.

dTree

Dynamic means moving in response to users.

Changing CSS properties

JavaScript allows you to change the CSS properties of an element when an event occurs.

Add the following JavaScript function under <script type="text/javascript"> of signUp2.html and create the signUp3.html using Save As menu.

function testCss() {
  var inputs = document.getElementsByTagName("input");
  for (var i = 0; i < inputs.length; i++) {
    inputs[i].style.background="yellow";
  }
}

Add the onload attribute to the body element. The onload event of the body element occurs when all elements of the document are downloaded and available.

<body onload="testCss()">

Run the example

Adding content

Facebook comments are an excellent example of adding content to a web page using JavaScript.

facebook comments

References