Ví dụ mã thực tế sử dụng JavaScript

Ví dụ 1: JavaBảng nhân tập lệnh

Tạo một bảng nhân đơn giản hỏi người dùng số hàng và số cột mà họ muốn.

Giải pháp:

<html>
<head>
  <title>Multiplication Table</title>
  <script type="text/javascript">
    var rows = prompt("How many rows for your multiplication table?");
    var cols = prompt("How many columns for your multiplication table?");
    if(rows == "" || rows == null)
   		 rows = 10;
    if(cols== "" || cols== null)
   		 cols = 10;
    createTable(rows, cols);
    function createTable(rows, cols)
    {
      var j=1;
      var output = "<table border='1' width='500' cellspacing='0'cellpadding='5'>";
      for(i=1;i<=rows;i++)
      {
    	output = output + "<tr>";
        while(j<=cols)
        {
  		  output = output + "<td>" + i*j + "</td>";
   		  j = j+1;
   		}
   		 output = output + "</tr>";
   		 j = 1;
    }
    output = output + "</table>";
    document.write(output);
    }
  </script>
</head>
<body>
</body>
</html>

Ví dụ #2: Ví dụ về Biểu mẫu JS:

Tạo một chương trình mẫu biểu mẫu thu thập tên, họ, email, ID người dùng, mật khẩu và xác nhận mật khẩu từ người dùng. Tất cả các đầu vào là bắt buộc và địa chỉ email nhập vào phải ở định dạng đúng. Ngoài ra, các giá trị nhập vào hộp văn bản mật khẩu và xác nhận mật khẩu phải giống nhau. Sau khi xác thực bằng JavaScript, Trong đầu ra, hiển thị thông báo lỗi thích hợp bằng màu đỏ ngay bên cạnh hộp văn bản có lỗi.

Giải pháp với Mã nguồn:

<html>
<head>
  <title>Form Validation</title>
  <script type="text/javascript">
    var divs = new Array();
    divs[0] = "errFirst";
    divs[1] = "errLast";
    divs[2] = "errEmail";
    divs[3] = "errUid";
    divs[4] = "errPassword";
    divs[5] = "errConfirm";
    function validate()
	{
      var inputs = new Array();
      inputs[0] = document.getElementById('first').value;
      inputs[1] = document.getElementById('last').value;
      inputs[2] = document.getElementById('email').value;
      inputs[3] = document.getElementById('uid').value;
      inputs[4] = document.getElementById('password').value;
      inputs[5] = document.getElementById('confirm').value;
      var errors = new Array();
      errors[0] = "<span style='color:red'>Please enter your first name!</span>";
      errors[1] = "<span style='color:red'>Please enter your last name!</span>";
      errors[2] = "<span style='color:red'>Please enter your email!</span>";
      errors[3] = "<span style='color:red'>Please enter your user id!</span>";
      errors[4] = "<span style='color:red'>Please enter your password!</span>";
      errors[5] = "<span style='color:red'>Please confirm your password!</span>";
      for (i in inputs)
      {
        var errMessage = errors[i];
        var div = divs[i];
        if (inputs[i] == "")
        	document.getElementById(div).innerHTML = errMessage;
        else if (i==2)
        {
          var atpos=inputs[i].indexOf("@");
          var dotpos=inputs[i].lastIndexOf(".");
          if (atpos<1 || dotpos<atpos+2 || dotpos+2>=inputs[i].length)
        	document.getElementById('errEmail').innerHTML = "<span style='color: red'>Enter a valid email address!</span>";
          else
        	document.getElementById(div).innerHTML = "OK!";
        }
        else if (i==5)
        {
          var first = document.getElementById('password').value;
          var second = document.getElementById('confirm').value;
          if (second != first)
        	document.getElementById('errConfirm').innerHTML = "<span style='color: red'>Your passwords don't match!</span>";
          else
       		document.getElementById(div).innerHTML = "OK!";
        }
        else
        	document.getElementById(div).innerHTML = "OK!";
       }
     }
        function finalValidate()
        {
          var count = 0;
          for(i=0;i<6;i++)
          {
            var div = divs[i];
            if(document.getElementById(div).innerHTML == "OK!")
            count = count + 1;
          }
          if(count == 6)
          	document.getElementById("errFinal").innerHTML = "All the data you entered is correct!!!";
        }
   </script>
</head>
<body>
	<table id="table1">
      <tr>
        <td>First Name:</td>
        <td><input type="text" id="first" onkeyup="validate();" /></td>
        <td><div id="errFirst"></div></td>
      </tr>
      <tr>
        <td>Last Name:</td>
        <td><input type="text" id="last" onkeyup="validate();"/></td>
        <td><div id="errLast"></div></td>
      </tr>
      <tr>
        <td>Email:</td>
        <td><input type="text" id="email" onkeyup="validate();"/></td>
        <td><div id="errEmail"></div></td>
      </tr>
      <tr>
        <td>User Id:</td>
        <td><input type="text" id="uid" onkeyup="validate();"/></td>
        <td><div id="errUid"></div></td>
      </tr>
      <tr>
        <td>Password:</td>
        <td><input type="password" id="password" onkeyup="validate();"/></td>
        <td><div id="errPassword"></div></td>
      </tr>
      <tr>
        <td>Confirm Password:</td>
        <td><input type="password" id="confirm" onkeyup="validate();"/></td>
        <td><div id="errConfirm"></div></td>
      </tr>
      <tr>
        <td><input type="button" id="create" value="Create" onclick="validate();finalValidate();"/></td>
        <td><div id="errFinal"></div></td>
      </tr>
	</table>
</body>
</html>

Ví dụ #3: Tin nhắn POPUP sử dụng Sự kiện:

Hiển thị một thông báo đơn giản “Chào mừng!!!” trên trang web demo của bạn và khi người dùng di chuột qua tin nhắn, một cửa sổ bật lên sẽ hiển thị với thông báo “Chào mừng đến với Trang web của tôi!!!”.

Giải pháp:

<html>
    <head>
        <title>Event!!!</title>
        <script type="text/javascript">
            function trigger() {
                document.getElementById("hover").addEventListener("mouseover", popup);
                function popup() {
                    alert("Welcome to my WebPage!!!");
                }
            }
        </script>
        <style>
            p{
                font-size: 50px;
                position: fixed;
                left: 550px;
                top: 300px;
            }
        </style>
    </head>
    <body onload="trigger();">
        <p id="hover">Welcome!!!</p>
    </body>
</html>