JavaScript Message Box

Background

I have often observed that users put their problems on the CodeProject forum related to JavaScript. They don't know the exact use of JavaScript. Why should we use it? Where to define it?

In this article, I will explain what JavaScript is, why JavaScript is used, how to use JavaScript for validation, functions, and properties, and some easy functions that you can copy and paste into your code. This resource is entirely about JavaScript.

Introduction

JavaScript is the most popular scripting language used in almost all browsers. The primary use of JavaScript is to validate user input. Besides that, JavaScript can be used for designing CSS, data manipulation, and more.

Including JavaScript to Page

JavaScript can be used with HTML, DHTML, XML, XHTML, ASP, JSP, ASPX, PHP, etc. JavaScript is defined in a separate block of HEAD. Let's see the following example; it will give you a clear idea.

<html>    
     <head>  
          <script language="JavaScript"> function CallMe(){alert("Yes..first POP up from javascript");return false;}</script>  
     </head>  
  
     <body> Welcome to javascript example!<input type="submit" id="sub1" onclick="return CallMe();"> </body>    
</html>  

Let's travel with the above code,

  • JavaScript defined under HEAD tag
  • We can write functions in JavaScript
  • the function is a reserved keyword
  • the alert is used for POP message
  • return false indicates the page should not submit to the server (means code execution will stop at that point)
  • We can call the JavaScript function using the onclick event
  • Like VBScript, we cannot change the caption of the POPup box in JavaScript

Using the Document Object

the document is the most commonly used object in JavaScript. We can collect any control from the page using a document as an object. Let's take an example.

Validating Page for empty textbox using document object

[now I am just giving an example through functions, you can call them on your page],

function ValidateME()     
{    
     if (document.getElementById("txtUserName").value == "")     
     {    
          alert("Please enter user Id rraannaammeett"); // Give alert to user    
          document.getElementById("txtUserName").focus(); // Set focus on textbox    
          return false;    
     }    
}    

Change the forecolor/backcolor of the page using the document object

function ChangeME()  
{  
     document.bgColor = "red"; //change the backcolor to RED    
     document.fgColor = "#338844"; //change the forecolor    
}  

Write on a page using the document object

function WriteME()   
{  
     document.write("I can write on page");  
}  

Access form controls using 'ALL' property (ALL property is a browser(IE) specific)

function GetControlValue()   
{  
     alert(document.all.txtUser.Value);  
}  

document object has numerous functions and properties. Here are some of them,

  • alinkColor - Specifies the color of activated links
  • domain - Gives domain name under which served you used for security purposes
  • title - Specifies the title of a document
  • cookie - A string containing the name/value pair of cookies in the document
  • FileSize - Return the file size of the current document
  • URL - A string that specifies the complete URL of the document
  • cookie - A string containing the name/value pair of cookies in the document

POP-UPs

The most famous part of JavaScript which the prompt user from the client side. Let's see how we can generate POP-UPs with some lines of code.

using alert

ALERT can be used to alert the user. A simple messagebox is accepted by all browsers.

Here is a small example

function giveAlert()   
{   
     alert("WOW ! this is alert");   
     return false;   
}  

using confirm

CONFIRM can be used to confirm user decisions. A simple messagebox with OK and CANCEL buttons. This function returns a boolean value. Here is a small example,

function askFor()   
{   
     if (confirm("Are you sure rraannaammeett"))   
          alert("Yes, i am sure rraannaammeett")  
     else   
          alert("No, i am not sure rraannaammeett")   
}  

using Prompt

This is used to accept input from users,

function EnterChoice()   
{   
     var reply = prompt("what is your name", "Enter your name")   
     alert("HI" + reply);   
}  

Here var is the datatype in JavaScript like integer, string, and "reply" is the variable.

Event Handling

JavaScript supports several events; here we go for the most common/used events.

onClick 

This event is supported mainly by all controls of the webform.

onClick handlers execute something only when users click buttons, links, checkboxes, radiobutton, etc.

<script>  
     function callME()  
     {  
          alert("yes..OnClick called!")  
     }  
</script>  
<form>   
     <input type="button" value="Click Me" onclick="callME()">   
</form>  

onchange

This event is fired by the combo box while changing items in the combo list. Here is an example of how to get a selected item from the dropdownlist.

<script>  
     function getItem()   
     {  
          alert("you select " + document.getElementById("idDDL").value)  
     }  
</script>  
<form>  
     <asp:Dropdownlist id="idDDL" runat="server" onchange="getItem()">  
          <listItem>a<listItem>  
     </asp:Dropdownlist>  
</form>  

onMouseover, onMouseout

These are exclusive events used when the mouse pointer is OVER and OUT from control.

<body>  
     <a href="#" onMouseOver="alert('Hi,I am mouse over rraannaammeett!">Over Here!</a>   
     <a href="#" onMouseOut="alert('Hin I am mouse out !')">Get Out Here!</a>  
</body>  

onUnLoad

This event calls JavaScript function while someone leaves the page, e.g., Giving a thanks message when the user leaves the page:

<body onunload="alert('Thank you for visiting rraannaammeett')">  

onblur

This event is called when any user leaves Textbox; it is the same as a LostFocus event in Winforms. e.g., we can validate if the user has left the textbox empty.

function ValidateInt()   
{  
     if (document.getElementById("txtNum").value == "")   
     {  
          alert("You can not left number field empty");  
          document.getElementById("txtNum").focus();  
          return false;  
     }  
}  

Working with Dates

Very few developers work with date in JavaScript. Here are some good examples to display today's date.

<HTML>  
  
     <HEAD>  
          <TITLE>Date using Javascript</TITLE>  
     </HEAD>  
  
     <BODY>  
          <SCRIPT LANGUAGE="JavaScript">  
          function CallMe()   
          {  
               var dt = new Date();  
               alert("Todays date is " + dt);  
          }  
          </SCRIPT>  
     </BODY>  
  
</HTML>  

Here are some functions that deal with date objects,

  • getTime() - Get the Number of milliseconds
  • getSeconds() - Get the Number of seconds (0-59)
  • getMinutes() - Get the Number of minutes (0-59)
  • getMinutes() - Get the Number of minutes (0-59)
  • getHours() - Get the Number of hours (0-23)
  • getDay() - Get Day of the week(0-6). 0 = Sunday, ... , 6 = Saturday
  • getDate() - Get Day of the month (0-31)
  • getMonth() - Get the Number of months (0-11)
  • getFullYear() - Get year range between(1970-9999)

Functions That Make Life Easy

Let's rock with the following functions that make life easy. You can call these functions on any event in your web application, like onclick, onblur, onchange, etc.

  1. Check if the Textbox has a numeric value,

    function checkInt()   
    {  
         if (isNAN(document.getElementById("txtNum").value))  
              alert("Please enter only numbers rraannaammeett");  
    }  

    *isNAN- The NaN property represents the "Not-a-Number" value. This method indicates that a value is not a legal number.

  2. Evaluate expression

    function checkInt()   
    {  
         function evaluateME()   
         {  
              alert(eval(2 + 2));  
         }  
    }  

    *eval- evaluates the expression and gets the output.

  3. Display only the specified length of the string

    function FormatMe()   
    {  
         var exNum = new Number(3.141516254);  
         alert(exNum.toPrecision(4));  
    } //Output : 3.141  

    *toPrecision()- This method formats a number to a specified length.

  4. Alert box with a line break

    We often need to display a message on different lines; here we go.

    function disp_alert()   
    {  
         alert("This is line 1 " + '\n' + "Yes, I am after line break rraannaammeett!");  
    }  

    *\n- Used to break lines.

  5. Get how many char's entered in the textbox

    function disp_char()   
    {  
         alert("You have entered " + document.getElementById("txtUser").length() + " chars);  
    }  

    *length()- Used to get the length of the textbox.

  6. Case Insensitive String Compare

    function ValidateCases()   
    {  
         var user1 = document.getElementById("txtUser").value;  
         if (user1.toLowerCase() == "Welcome".toLowerCase())  
              alert("Welcome matched");  
         else alert("Access Denied!");  
    }  

    *toLowerCase()- Convert string to lowercase.

  7. Split string with javascript

    The following code is used to split string values with specified split char,

    function SplitME()   
    {  
         var myString = "str1/str2";  
         var mySplitResult = myString.split("/");  
         alert("The first element is " + mySplitResult[0]);  
         alert("The second element is " + mySplitResult[1]);  
    }  

    *split()- This method splits the string with specified char.

  8. Validate EMail address

    The following code is used to validate an email address with Regular expressions,

    function ValidateEmail()   
    {  
         var pattern = "/^\w+@[a-zA-Z_]+?\.[a-zA-Z]{2,3}$/";  
         str = "[email protected]";  
         alert(str.match(pattern));  
         return false;  
    }  
  9. Showing/Hiding controls on a specific condition

    A lot of times, we need to Hide/show control against a specific condition. Here is the function which will help us to TOGGLE the view of the state and pass the control id to the following function,

    function Toggle(obj)   
    {  
         var ctrlid = document.getElementById(obj);  
         if (ctrlid.style.display != 'none')  
              ctrlid.style.display = 'none';  
         else  
              ctrlid.style.display = '';  
    }  
  10. Prevent ENTER key on Textbox

    Call the following function on the keypress event of Textbox.

    function avoidEnter()   
    {  
         if (event.keyCode == 13)  
              return false;  
    }  
  11. Disabled RIGHT click using Javascript.

    If you need to disable it right, click on Textbox / Document and use the following function:

    function DisableRight()   
    {  
         if (event.button == 2)  
              return false;  
    }  

    * for textbox, call the above function on the OnCLIENTCLICK event * for the document, call the above function on the ONCLICK event of BODY

  12. Debugging JavaScript with Visual Studio

    You can debug the JavaScript functions by adding a debugger; keyword in the function. But before starting debugging, make sure that your debugging is enabled for the script in Internet Explorer. To check the setting, go to Internet Explorer --> Tools --> Internet Options --> Advanced Tab.

    Debugger Setting