Pages

Tuesday, January 10, 2012

Java Script


OnClick Script:
deleteButton.Attributes.Add("onclick", "javascript:return confirm('Are you sure you want to delete this record?')";

Use Regular Expression to validate date:

<html>
<head>
<title>Date Example</title>
<script type="text/javascript">
    function isValidDate(sText) {
        var reDate = /(?:0[1-9]|[12][0-9]|3[01])\/(?:0[1-9]|1[0-2])\/(?:19|20\d{2})/;
        return reDate.test(sText);
    }
    function validate() {
        var oInput1 = document.getElementById("txt1");
        if (isValidDate(oInput1.value)) {
            alert("Valid");
        else {
            alert("Invalid!");
        }

    }
</script>
</head>
<body>
    <P>Date: <input type="text" id="txt1" /><br />
    example: 05/05/2005<br />
    <input type="button" value="Validate" onclick="validate()" /></p>
</body>
</html>


Checking an email address - Version 01:

<html>
<head>
<title>Checking an email address - Version 01</title>
<script type="text/javascript" language="javascript">
<!-- //
function IsMatchingAddress(str){
    var myRegExp = /[a-z0-9-]{1,30}@[a-z0-9-]{1,65}.[a-z]{3}/ ;
    return myRegExp.test(str)
}

function TestGuess(){

var EmailAddr = "asdf@asdf.net".toLowerCase();
alert(IsMatchingAddress(EmailAddr));
}
// -->
</script>
</head>
<body>
<h3>This page allows you to enter and check
 an email address such as asdf@java2s.com.com</h3>
<form>
<button type="Button" onclick="TestGuess()">
Click here to enter email address</button>
</form>
</body>
</html>


Use Regular expression to validate the Email:

<html>
<head>
<title>E-mail Example</title>
<script type="text/javascript">
    function isValidEmail(sText) {
        var reEmail = /^(?:\w+\.?)*\w+@(?:\w+\.)+\w+$/;
        return reEmail.test(sText);
    }
    function validate() {
        var oInput1 = document.getElementById("txt1");
        if (isValidEmail(oInput1.value)) {
            alert("Valid");
        else {
            alert("Invalid!");
        }

    }
</script>
</head>
<body>
    <P>E-mail Address: <input type="text" id="txt1" /><br />
    <input type="button" value="Validate" onclick="validate()" /></p>

</body>
</html>


Use regular expression to validate the URL:

<HTML>
<HEAD>
<SCRIPT language="JavaScript">
<!--

function check_it()
{
     var theurl=document.myForm.t1.value;
     var tomatch= /http:\/\/[A-Za-z0-9\.-]{3,}\.[A-Za-z]{3}/

     if (tomatch.test(theurl)){
         window.alert("URL OK.");
         return true;
     }
     else
     {
         window.alert("URL invalid. Try again.");
         return false;
     }
}
//-->
</SCRIPT>
</HEAD>
<BODY>
<FORM name="myForm" action="#" onSubmit="return check_it();">
Enter URL:<BR>
<INPUT type="text" name="t1">
<BR>
<INPUT type="submit" value="Submit">
</BODY>
</HTML>


Date subtraction:

<html>
<head>
<title>Date substraction</title>
</head>
<body>
<script language="JavaScript" type="text/javascript">
<!--

var myVar = prompt("Enter a future date: ")

var user_date = Date.parse(myVar);
var today_date = new Date();
var diff_date =  user_date - today_date;

document.write(diff_date);
//-->
</script>
</body>
</html>


Get year, month and day from date difference:

<html>
<head>
<title>Date substraction</title>
</head>
<body>
<script language="JavaScript" type="text/javascript">
<!--

var myVar = prompt("Enter a future date: ")

var user_date = Date.parse(myVar);
var today_date = new Date();
var diff_date =  user_date - today_date;

var num_years = diff_date/31536000000;
var num_months = (diff_date % 31536000000)/2628000000;
var num_days = ((diff_date % 31536000000) % 2628000000)/86400000;

document.write("Number of years: " + Math.floor(num_years) + "<br>");
document.write("Number of months: " + Math.floor(num_months) + "<br>");
document.write("Number of days: " + Math.floor(num_days) + "<br>");
//-->
</script>
</body>
</html>

Convert Time:

<html>
<head>
<title>Convert Time</title>
</head>
<body>
<script language="JavaScript" type="text/javascript">
<!--

var current_date = new Date();
var hour_value = current_date.getHours();
var minute_value = current_date.getMinutes();
var second_value = current_date.getSeconds();
var AMorPM = "AM";

if (hour_value > 12)
{
  hour_value -= 12;
  AMorPM = "PM";
}

if (hour_value == 0)
   {
   hour_value = 12;
   AMorPM = "AM";
}

if (second_value < 10)
{
  second_value = "0" + second_value;
}

if (minute_value < 10)
{
  minute_value = "0" + minute_value;
}

document.write("The current time is " + hour_value + ":" +
minute_value + ":" + second_value + " " + AMorPM);

//-->
</script>
</body>
</html>

http://www.codeproject.com/KB/scripting/DOMAlert/DOMAlert.png
Introduction
Alert boxes in JavaScript are notoriously unforgiving when it comes to designing a user interface. You cannot add images, change the background color, or otherwise "theme" the dialog to match the style of your web page or web application. Fortunately, JavaScript in conjunction with the Document Object Model (DOM) is there to help us achieve an otherwise unobtainable goal.
Background
This is my second attempt at creating a JavaScript alert box. My first attempt was a few years ago. The code was buggy and difficult to use, so I put it on the backburner with the intention of doing a complete rewrite. I recently began upgrading the web application that made use of the old code, and decided that it was time to breath life into the old code.
There are a number of similar alert boxes on the web, but most are part of larger projects, or make use of external libraries.
Using the Code
To use the custom alert/dialog boxes, you must add the JavaScript source to your header, as well as the .css files that determine the "skin" the boxes will use.
http://www.codeproject.com/images/minus.gifCollapse
<link rel="Stylesheet" href="default.css" type="text/css" media="screen" />
<script type="text/javascript" src="DOMAlert.js"></script>
If you fail to include a reference to a stylesheet, the .js file will look for default.css in the local path.
Once you have added your .js and .css files, you can create a new alert box by using the following constructor:
http://www.codeproject.com/images/minus.gifCollapse
var msg = new DOMAlert(
{
    title: 'Title',
    text: 'Alert Message',
    skin: 'default',
    width: 300,
    height: 300,
    ok: {value: true, text: 'Yes', onclick: showValue},
    cancel: {value: false, text: 'No', onclick: showValue }
});
The constructor takes only one argument, an object containing one or more of the following properties:
  • title: The title of the alert box. Can contain inline HTML, but may not render correctly. Optional. Can be passed in the show() method.
  • text: The text of the alert box. Can contain inline HTML, but may not render correctly. Optional. Can be passed in the show() method.
  • skin: The skin to use for the alert box. Skins/themes are discussed later in this article.
  • width: The width of the alert box. Optional, but recommended.
  • height: The height of the alert box. Optional.
  • ok: An object containing the text of the 'OK' button, the callback to be pressed when that button is clicked (onclick), and the value passed to that callback. The default is to call the close() method of the alert box. Optional, but recommended.
  • cancel: An object containing the text of the 'Cancel' button, the callback to be pressed when that button is clicked, and the value passed to that callback. There is no default.
Methods
The following methods are currently supported:
  • show(): Changes the visible state of the alert box to visible.
  • show(text): Changes the visible state of the alert box, and sets the text of the alert. If using this method, title must be set in the constructor.
  • show(title, text): Changes the visible state of the alert box to visible, and sets both the title and the text of the alert box.
  • hide(): Changes the visible state of the alert box to hidden.
  • close(): Destroys all HTML elements attached to the alert box and unregisters all the onclick callbacks. This does not destroy the object or its methods since they are prototyped.
  • center(): Centers the alert box on the page. Most users shouldn't need to call this, as it is called automatically.
Callback
The callbacks for the OK and Cancel buttons can either be references to an existing function or a closure. For pre-existing functions, two objects are passed as arguments, a reference to the alert box that the OnClick event was generated from, and the value of the button that was clicked.
http://www.codeproject.com/images/minus.gifCollapse
function showValue(sender, value)
{
    //sender is the alert box that the event was called from
    //value is the value that was passed from the pressed button
}
Skins/Themes
The .js file contains little to no information regarding the design of the alert box, only the layout. Since users may have different requirements in the design on a per alert box basis, and to separate design from code, the design information resides in .css files. If no skin information is provided, the code looks for a 'default.css' file to be located in the current directory. Each CSS name needs to be prefixed with the name of the skin you wish to use. So, if your theme is named 'human' and you are defining the contentArea, then your CSS name needs to be .human_contentArea.
This allows you to include all your skin information in one .css file, or in multiple ones. It's entirely up to you. However, some aspects like position or width may be overwritten in the .js file.
The following style names can be used:
  • alertWindow: The main alert window.
  • titleBar: The title bar.
  • titleBarLeftIcon: A div that has its style set to float: left.
  • titleBarRightIcon: A div that has its style set to float: right.
  • contentArea: The content area where your text will go.
  • buttonArea: The area that contains your buttons.
  • okButton: Your 'OK' button.
  • cancelButton: Your 'Cancel' button.
Bugs
IE6. Do I really need to say any more?
  • IE6 doesn't support the fixed property. If you want the alert box to stay in the center of the page if the user scrolls, you will need to add your center() method to your window.onscroll event.
  • Select elements will render above other elements, regardless of their z-index. The exception to this rule is an iframe. The script will check to see if you are using IE6 and if so, it will add an iframe behind the alert box to hide the select elements.
  • To simulate modality and opacity, a semi-transparent .png image is used. However, select elements can still be activated. You'll probably want to disable your select elements and re-enable them at the appropriate times.
Points of Interest
The 'filter' property in Internet Explorer has a memory leak when using 'alpha(opacity=##)', even after the owning DOM object is removed. As a result, a semi-transparent .png is used instead. This works well except in IE6, which doesn't support transparent .png files very well. Instead, I used the proprietary AlphaImageLoader when the script detects that the browser is IE6.

Validating Form Fields Using JavaScript in FrontPage
Lisa Wollin
Microsoft Corporation
May 2004
Applies to:
    Microsoft® Office FrontPage® 2003
    Microsoft FrontPage 2002
    Microsoft FrontPage 2000
Summary: Learn how validate HTML form fields using JavaScript in Microsoft Office FrontPage 2003. This article assumes a general understanding of HTML and JavaScript. (16 printed pages)

Contents

Introduction
Getting Started
Writing the Validation Script
Connecting the Form to the Script
Associating Form Fields with Custom Script
Code Listing
Conclusion

Introduction

When you create forms, providing form validation is useful to ensure that your customers enter valid and complete data. For example, you may want to ensure that someone inserts a valid e-mail address into a text box, or perhaps you want to ensure that someone fills in certain fields.
Microsoft® Office FrontPage® 2003 allows you to create some custom validation within the form feature. (For more information on how to create form validation using the FrontPage form feature, see About creating forms in FrontPage 2003.) However, if the form validation provided in FrontPage does not suit your needs or the site on which you are working is hosted on a server that does not have FrontPage Server Extensions from Microsoft installed, you may need to create custom form validation.
Note   FrontPage Server Extensions are a set of programs that provide access to special FrontPage features, such as database processing, form processing, hit counters, and other built-in FrontPage components that require server-side processing.
You can provide custom validation for your forms in two ways: server-side validation and client-side validation.
Server-side validation incorporates code validation into a form handler. For example, you may have an ASP or ASP.NET application on the server that provides the functionality that your form needs for processing after a customer has submitted it. Because the code is stored on the server, server-side validation requires a roundtrip to the server. Sending data back and forth between the client and server can cause some delays. However, for some form functions, server-side validation is necessary. For example, if you have a form that populates a drop-down list based on the value of another form field, server-side processing may be needed to pull data from a database and populate the drop-down list.
Client-side validation provides validation within the browser on client computers through JavaScript. Because the code is stored within the page or within a linked file, it is downloaded into the browser when a user accesses the page and, therefore, doesn't require a roundtrip to the server. For this reason, client form validation can be faster than server-side validation. However, client-side validation may not work in all instances. A user may have a browser that doesn't support client-side scripting or may have scripting disabled in the browser. Knowing the limits of client-side scripting helps you decide whether to use client-side form validation.
This article explains how to provide client-side validation for forms that you create either by hand or by using the form tools within FrontPage. In addition, this article assumes a general understanding of HTML and JavaScript, although a thorough understanding is not required. For more information about HTML and Web scripting, see one or more of the following references.
Important   JScript is Microsoft's implementation of ECMAScript, as defined by the specification of the European Computer Manufacturers Association. Both JavaScript and JScript are ECMAScript-compliant languages. When referring to JavaScript in general, this article uses the generally accepted term "JavaScript." However, when referring to documentation on the Microsoft Developer Network (MSDN) Web site, this article uses the term "JScript."

Getting Started

To get started, you need a form. For the purposes of this article, paste the following form into a new page in FrontPage in Code view.
Note   To do this, create a new page, switch to Code view, and paste the following code between the <body> and </body> tags.
<form method="post" action="mailto:Frank@cohowinery.com">
    <p>Name: <input type="text" size="65"></p>
    <p>E-mail Address:  <input type="text" size="65" ></p>
    <p>Telephone: <input type="text" size="65"><br>
        <input type="checkbox"> Please do not call me.</p>
    <p> What can we help you with?
        <select type="text" value="">
            <option>  </option>
            <option>Customer Service</option>
            <option>Question</option>
            <option>Comment</option>
            <option>Consultation</option>
            <option>Other</option>
        </select></p>
    <p>Comments:  <textarea cols="55">  </textarea></p>
    <p><input type="submit" value="Send" name="submit"><br>
    <input type="reset" value="Reset" name="reset"></p>
</form>
 
Code Sample 1. Starting form code
As you work through this article, you are asked to add or change portions of the previous code.
Note   The previous code specifies an e-mail address for the Action attribute of the form property. For more information, see ACTION Attribute | action Property and form property. The action attribute tells the browser what to do when a user submits the form. If you want to test this form, change this e-mail address to your own e-mail address.

Assigning Names to Form Fields

In order to access your form fields in code, you need to assign names to the form and each of the fields. You do this by using the Name attribute. For more information see, NAME Attribute | name Property. You may assign any name you want that is composed of alphanumeric characters (without spaces), but to make writing the code easiest, you should provide a useful, friendly name for each of the fields. In addition, each of the fields should have a unique name.
Note   Generally, it is a good idea to provide a name attribute for each HTML element that you plan on accessing in code.
In the code provided previously you can find the following line.
<p>Name: <input type="text" size="65"></p>
 
When you add the name attribute, the code looks like the following:
<p>Name: <input type="text" size="65" name="Name"></p>
 
Use the following table to assign names to all of your form elements. In this table, Element refers to the name of the HTML element for the form field, Type refers to the value of the type attribute for the form field, and Label refers to the text to the left of the form field.
Element
Type
Label
Name
FORM
(not applicable)
(none)
ContactForm
INPUT
text
Name
Name
INPUT
text
E-mail Address
Email
INPUT
text
Telephone
Telephone
INPUT
checkbox
Please do not call me.
DoNotCall
SELECT
text
What can we help you with?
Subject
TEXTAREA
(not applicable)
Comments
Comment
Once you have assigned names for your form and all of the form elements, your form code should resemble the following code.
<form method="post" action="mailto:Frank@cohowinery.com" name="ContactForm">
    <p>Name: <input type="text" size="65" name="Name"></p>
    <p>E-mail Address:  <input type="text" size="65" name="Email"></p>
    <p>Telephone: <input type="text" size="65" name="Telephone"><br>
        <input type="checkbox" name="DoNotCall"> Please do not call me.</p>
    <p>What can we help you with?
        <select type="text" value="" name="Subject">
            <option>  </option>
            <option>Customer Service</option>
            <option>Question</option>
            <option>Comment</option>
            <option>Consultation</option>
            <option>Other</option>
        </select></p>
    <p>Comments:  <textarea cols="55" name="Comment">  </textarea></p>
    <p><input type="submit" value="Send" name="submit"><input type="reset" value="Reset" name="reset"></p>
</form>
 
Code Sample 2. Form code updated with name attribute values

Writing the Validation Script

Now that you have assigned names for the form and form fields, you are ready to start writing the script that handles the validation for the fields.
Important   JavaScript is case sensitive. If you are typing the JavaScript code in this article manually and receive errors, you should check that all casing is the same as shown in this article. Otherwise, you may want to review JScript Run-Time and Syntax errors.

Creating the Function

You need a custom function that you can later connect to the form. For more information about creating a function, see JScript Functions. A function is a piece of code that consists of one or more lines of script. A function can take arguments and can return values. The validation script in this article returns a Boolean value that specifies whether the data contained in the form is valid.
To create your own custom function, insert a SCRIPT element into the HEAD section of your form page; within the SCRIPT element, use the function statement to insert a function named ValidateContactForm. For more information, see function Statement. This code should look something like the following code sample.
<script>
function ValidateContactForm()
{
 
}
</script>
 
Code Sample 3. Starting script function

Creating Field Variables

To access the form fields within the code, you should create variables. For more information, see JScript variables. Variables allow you to temporarily store values. Variables are not required, but they make accessing each field easier. For example, without a variable, you would have to type document.ContactForm.Name every time you needed to access the Name field. However, after you assign a variable to the field, you can use the variable to access the field. Variables require less typing and help make your code more readable.
The contact form code in this article contains six fields to which you assigned name attribute values; therefore, you need six variables, one for each field. The following code shows the ContactForm Validation function with variables for the six form fields.
function ValidateContactForm()
{
    var name = document.ContactForm.Name;
    var email = document.ContactForm.Email;
    var phone = document.ContactForm.Telephone; 
    var nocall = document.ContactForm.DoNotCall;
    var what = document.ContactForm.Subject;
    var comment = document.ContactForm.Comment;
}
 
Code Sample 4. Script function with variables
Note   If you type the previous code into your page, notice that FrontPage provides IntelliSense for your named fields.

Defining Required Fields

You may want to require that users type something for some fields on your form. By default, when you first create a form, all fields are optional. Therefore, if you want to ensure that users fill in certain fields, you need to tell the form validation function to check each field by checking the value of the field. In most cases, just checking whether the field contains a value is sufficient for a required field. In the following example, the if statement determines whether the Name field contains a value by checking whether the value of the Name field is equal to a empty string. For more information, see if. . .else Statement.
if (name.value == "")
{
    window.alert("Please enter your name.");
    name.focus();
    return false;
}
 
If the user clicks the Submit button without entering a value in the Name field, the browser displays a message to remind the user to enter a name. The Insertion Point is placed in the Name field, and the user is returned to the form. The return statement with a value of false is necessary so that the rest of the code doesn't execute. For more information, see return Statement.
For the contact form in this article, you also need a validation if statement for the comment field. The following code checks whether a user has entered a value in the comment field.
if (comment.value == "")
{
    window.alert("Please provide a detailed description or comment.");
    name.focus();
    return false;
}
 
You can add a similar if statement to verify that the user has selected an item from the What can we help you with drop-down list. In this case, you don't check the value of the field; you check the value of the selected item. The following code shows the validation for the What can we help you with drop-down list.
if (what.selectedIndex < 1)
{
    alert("Please tell us how we can help you.");
    what.focus();
    return false;
}
 
Items in a drop-down list or list box begin numbering at zero, so if the index of the selected item is less than 0, the user hasn't selected anything. However, the first OPTION element in the Subject field in the contact form is blank. (A space is used to keep the tag pair from being empty.) This technique allows no value to be displayed in the list when the form page first loads, so the first valid item in the list is numbered 1. Therefore, the previous if statement requires that the selected item index be less than 1.

Determining Whether Data Is Valid

In some cases, you may want to verify that the data is valid based on a specified format. For example, you know that all e-mail addresses contain an at symbol (@) and at least one period (.). For the e-mail address, the if statement needs to be slightly more detailed to check for the needed values. In addition, because you need to check for multiple values, you need multiple if statements. In this case, there are three if statements: one to check whether the e-mail field contains a value, the second to check whether the e-mail string contains an @ symbol, and the third to check whether the e-mail string contains a period.
The second and third if statements use the indexOf method to determine whether a string occurs within another string. For the e-mail address, you need to determine whether an @ symbol or a period occurs within the e-mail form field. If the value returned from the indexOf method is less than zero (or –1), the e-mail address is invalid, the validate function returns false, and focus is returned to the e-mail form field.
The following code shows validation for the Email field.
if (email.value == "")
{
    window.alert("Please enter a valid e-mail address.");
    email.focus();
    return false;
}
 
if (email.value.indexOf("@", 0) < 0)
{
    window.alert("Please enter a valid e-mail address.");
    email.focus();
    return false;
}
 
if (email.value.indexOf(".", 0) < 0)
{
    window.alert("Please enter a valid e-mail address.");
    email.focus();
    return false;
}
 
Multiple if statements have a cascading effect. If the first if statement indicates that the e-mail address contains a value, the second if statement runs, and if the second if statement indicates that the e-mail address contains an @ symbol, the third if statement runs. If any of the three if statements indicate an invalid e-mail address, a message is displayed to the user, the validation function returns false, and the user is returned to the form with the Insertion Point in the Email field.
You can also create a similar if statement for telephone numbers. If you specify the format for telephone numbers, you can use the indexOf method to determine whether a specified string (which in some cases is a hyphen [-]) occurs within the telephone form field. If the indexOf method returns a –1, the telephone number does not contain a hyphen.

Returning a Value from a Function

You can return a value from a custom function by using the return statement. As mentioned previously, each of the if statements shown previously contains a line that returns a Boolean value of false. When the validation function returns to the form, the return value tells the form whether to continue processing. A value of false tells the browser to stop processing the form. Therefore, at the end of the validation function, you also need a statement to return a value of true. This means that all form fields have validated and the form can continue processing.

Complete Form Validation Script

The following code sample shows the complete ValidateContactForm function for the contact form.
function ValidateContactForm()
{
    var name = document.ContactForm.Name;
    var email = document.ContactForm.Email;
    var phone = document.ContactForm.Telephone;
    var nocall = document.ContactForm.DoNotCall;
    var what = document.ContactForm.Subject;
    var comment = document.ContactForm.Comment;
 
    if (name.value == "")
    {
        window.alert("Please enter your name.");
        name.focus();
        return false;
    }
    
    if (email.value == "")
    {
        window.alert("Please enter a valid e-mail address.");
        email.focus();
        return false;
    }
    if (email.value.indexOf("@", 0) < 0)
    {
        window.alert("Please enter a valid e-mail address.");
        email.focus();
        return false;
    }
    if (email.value.indexOf(".", 0) < 0)
    {
        window.alert("Please enter a valid e-mail address.");
        email.focus();
        return false;
    }
 
    if ((nocall.checked == false) && (phone.value == ""))
    {
        window.alert("Please enter your telephone number.");
        phone.focus();
        return false;
    }
 
    if (what.selectedIndex < 1)
    {
        alert("Please tell us how we can help you.");
        what.focus();
        return false;
    }
 
    if (comment.value == "")
    {
        window.alert("Please provide a detailed description or comment.");
        comment.focus();
        return false;
    }
    return true;
}
 
Code Sample 5. Complete ValidateContactForm function

Connecting the Form to the Script

After you write the validation function, you need to tell your form to run the script when someone clicks the Submit button. To do this, you need to use the onsubmit event for the form. For more information, see onsubmit Event. (The onsubmit event occurs every time a form is submitted for processing, but it happens on the client side, so if all processing is done on the server, you don't need the onsubmit event.)
To cause your validation script to run every time a user submits the contact form, add the following code to the opening <form> tag.
onsubmit="return ValidateContactForm();"
 
Now you are ready to display your form in a browser and test the script, which you can do by filling the form fields with invalid data and clicking the Submit button.

Associating Form Fields with Custom Script

Sometimes you may want to respond when users select certain fields. For example, when a user clicks a button or selects a check box, you may want to enable or disable another field, display a secondary form page, or just display a message. Events allow you to respond to such situations.
An event is something that occurs within the browser or something that occurs as a result of something that a user does. For example, the onload event occurs every time a page loads and the onclick event occurs every time a user clicks something contained within the page. For more information, see onload event and onclick event. Events enable the browser to perform a certain action when a specific action occurs.
You can respond to user events in two ways.
  • Add the event script inline within the opening tag for the element
  • Add the event to the element with a reference to a custom function
In the contact form is a check box named DoNotCall. When a user selects this check box, the browser disables the Telephone field so that the user cannot enter a value. The following sections show how to disable the Telephone field using both methods.

Using Inline Event Scripting

If the script is simple, you can easily add the script for the event inline with the element. Although you can add multiple commands to an inline script, placing longer script code into a custom function makes the function more readable and thus easy to debug, or find errors in the code.
The following code shows how to handle the onclick event for the DoNotCall check box field. In this code, if the check box is checked, the Telephone field is disabled.
onclick="if(this.checked==true){document.ContactForm.Telephone.disabled = true;}"
 
You can insert this into the DoNotCall field in your form to see how it functions. In this case, the inline code doesn't function well because if a user selects the check box and then clears it, the Telephone field never becomes enabled again. In this case, a longer script is required. The following section shows you how to create a custom function for the event.

Using an Event Handler Function

Creating a function in response to an event is the same as creating any other function. Instead of adding the event script to the event in the opening tag of the element, you add the name of the function that handles the event.
As shown in the previous section, you need the Telephone field disabled if the DoNotCall field is checked. But if the DoNotCall field is cleared, the Telephone field should be re-enabled. The following function shows how to do this using an if. . .else statement.
function EnableDisable(chkbx)
{
    if(chkbx.checked == true)
    {
        document.ContactForm.Telephone.disabled = true;
    }
    else
    {
        document.ContactForm.Telephone.disabled = false;
    }
}
 
After you created the custom function, you can add the following code tag for the DoNotCall field.
onclick="EnableDisable(this);"
 
Notice that the EnableDisable function takes an argument. Therefore, when you call the event from within the element, you need to pass a value. In this case, you need to pass the current element, and the easiest way to do so is to use the this statement. For more information, see this Statement.

Code Listing

The following listing shows the complete code for the example in this article.
<html>
 
<head>
<title>Form Validation Example</title>
 
<script>
function ValidateContactForm()
{
    var name = document.ContactForm.Name;
    var email = document.ContactForm.Email;
    var phone = document.ContactForm.Telephone;
    var nocall = document.ContactForm.DoNotCall;
    var what = document.ContactForm.Subject;
    var comment = document.ContactForm.Comment;
 
    if (name.value == "")
    {
        window.alert("Please enter your name.");
        name.focus();
        return false;
    }
    
    if (email.value == "")
    {
        window.alert("Please enter a valid e-mail address.");
        email.focus();
        return false;
    }
    if (email.value.indexOf("@", 0) < 0)
    {
        window.alert("Please enter a valid e-mail address.");
        email.focus();
        return false;
    }
    if (email.value.indexOf(".", 0) < 0)
    {
        window.alert("Please enter a valid e-mail address.");
        email.focus();
        return false;
    }
 
    if ((nocall.checked == false) && (phone.value == ""))
    {
        window.alert("Please enter your telephone number.");
        phone.focus();
        return false;
    }
 
    if (what.selectedIndex < 1)
    {
        alert("Please tell us how we can help you.");
        what.focus();
        return false;
    }
 
    if (comment.value == "")
    {
        window.alert("Please provide a detailed description or comment.");
        comment.focus();
        return false;
    }
    return true;
}
 
function EnableDisable(chkbx)
{
    if(chkbx.checked == true)
    {
        document.ContactForm.Telephone.disabled = true;
    }
    else
    {
        document.ContactForm.Telephone.disabled = false;
    }
}
</script>
</head>
 
<body>
 
<form method="post" action="mailto:Frank@cohowinery.com" 
name="ContactForm" onsubmit="return ValidateContactForm();">
    <p>Name: <input type="text" size="65" name="Name"></p>
    <p>E-mail Address:  <input type="text" size="65" name="Email"></p>
    <p>Telephone: <input type="text" size="65" name="Telephone"><br>
        <input type="checkbox" name="DoNotCall" 
        onclick="EnableDisable(this);"> Please do not call me.</p>
    <p>What can we help you with?
        <select type="text" value="" name="Subject">
            <option>  </option>
            <option>Customer Service</option>
            <option>Question</option>
            <option>Comment</option>
            <option>Consultation</option>
            <option>Other</option>
        </select></p>
    <p>Comments:  <textarea cols="55" name="Comment">  </textarea></p>
    <p><input type="submit" value="Send" name="submit">
    <input type="reset" value="Reset" name="reset"></p>
</form>
 
</body>
</html>
 
<script type="text/javascript" language="javascript" src="Common/javascript/valjavavalidate.js"></script>
 
 
<script language="javascript" type="text/javascript">
   
var emailfilter=/^\w+[\+\.\w-]*@([\w-]+\.)*\w+[\w-]*\.([a-z]{2,4}|\d+)$/i
 
function checkmail(e){
var returnval=emailfilter.test(e.value)
if (returnval==false){
alert("Please enter a valid email address.")
e.focus();
 
}
return returnval
}
 
 
 
        function ValidateDataSub()
    {
        //alert();
        //return false;
        
        var email = 'txtemail';
        
        if(checkempty(document.getElementById("txtemail"),"Please Enter the email Id")==false)return false;
        if(document.getElementById("txtemail").value=="Email Id")
        {
            alert("Please Enter the Email Id");
            document.getElementById("txtemail").focus();
            return false;
        }
        
       
        
         if(checkmail(document.getElementById("txtemail")) == false)
         {
            //alert('hi');
            return false
         }
        //if(checkemail(document.getElementById("txtemail"),"Please Enter valid Email Id")==false)return false;
        return true;
    }
    function ClearText()
    {    
        var email = 'txtemail';
        document.getElementById("txtemail").value="";
        document.getElementById("txtemail").focus();
        
    }   
    function callout()
    {
        
       var email = 'txtemail';
     
       if(document.getElementById("txtemail").value == "")
       { 
           document.getElementById("txtemail").value="Email Id";
               
       }
    }
  
  </script>
 
 
<style type="text/css">
<!--
@import url("Common/Style/bpcl_style.css");
-->
</style>
        <link rel="stylesheet" type="text/css" href="Flash/main.css" />
               
               
               
               <script src="Flash/js/jquery-1.2.6.min.js" type="text/javascript"></script>
               <script src="Flash/js/jquery.easing.1.3.js" type="text/javascript"></script>
               <script src="Flash/js/jquery.kwicks-1.5.1.pack.js" type="text/javascript"></script>
               
               
               
               <script type="text/javascript">
                       $().ready(function() {
                               $('.kwicks').kwicks({
                                      max : 351,
                                      spacing : 1
                               });
                       });
               </script>
 
</head>
<body >
<form name="form1" method="post" action="index.aspx" id="form1">
<div>
<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwULLTE5OTM4ODIzNTAPZBYCAgMPZBYWAgEPZBYEAgEPD2QWAh4Hb25jbGljawUUcmV0dXJuIFNwZWVkU2VhcmNoKClkAgMPD2QWAh8ABRJyZXR1cm4gVGFnU2VhcmNoKClkAgUPFgIeCWlubmVyaHRtbAUGNTAzLjUwZAIHDxYCHwEFBjUwMS45MGQCCQ8WAh8BBQY1MDYuNTBkAgsPFgIfAQUGNDkyLjAwZAINDxYCHwEFFzMwIEFwciAxMS4yMTo1NCBBTSAgSVNUZAIRDxYCHgRocmVmBRhodHRwOi8vd3d3LnBldHJvdGVjaC5pbi8WAgIBDxYCHgNzcmMFNi9BZG1pbi9CYW5uZXIvVXBsb2RlZEltYWdlLzU1X1BldHJvdGVjaDIwMTBfYmFubmVyLmdpZmQCEw8PFgIeBFRleHRlZGQCFQ9kFgYCAQ8WBB8BBSxJbmRpYTogRUdPTSB0byBkZWNpZGUgb24gZnJlZWluZyBmdWVsIHByaWNlcx8CBTRZb3VyQ29ybmVyL1BldHJvRGFpbHlEZXRhaWxzLmFzcHg/UG5ld3NpZD1QMDAwMDI3MTM4ZAIDDxYEHwEFO0xvayBTYWJoYSBwYXNzZXMgRmluYW5jZSBCaWxsIHdpdGggbm8gY2hhbmdlIGluIGZ1ZWwgbGV2aWVzHwIFNFlvdXJDb3JuZXIvUGV0cm9EYWlseURldGFpbHMuYXNweD9QbmV3c2lkPVAwMDAwMjcxNDBkAgUPFgQfAQUuQlBDTCB0byBhbm5vdW5jZSBGWSAxMCByZXN1bHRzIG9uIE1heSAyNywgMjAxMB8CBTRZb3VyQ29ybmVyL1BldHJvRGFpbHlEZXRhaWxzLmFzcHg/UG5ld3NpZD1QMDAwMDI3MTQ2ZAIXDxYCHwEFDzx0YWJsZT48L3RhYmxlPmQCHQ8PZBYCHwAFGHJldHVybiBWYWxpZGF0ZURhdGFTdWIoKWQYAQUeX19Db250cm9sc1JlcXVpcmVQb3N0QmFja0tleV9fFgMFFkhlYWRlcjEkaW1nU3BlZWRTZWFyY2gFFEhlYWRlcjEkaW1nQnRuU2VhcmNoBQVpbWdHb9b3uOA0pTPiUZobDwu7bhhyG0mL" />
</div>
 
<div>
 
        <input type="hidden" name="__EVENTVALIDATION" id="__EVENTVALIDATION" value="/wEWBwK3hfDWAQLk4JvzBwL8lYOFBgLohLniAwKP4braDgKE8/3/CQKryeHrBtvYZEOvRvJmy6iXCSsylBapAJQB" />
</div>
  <div id="container">
    <div id="contarea">
      <div id="header">
        
<link rel="shortcut icon" href="../../images/bpcl_ico.ico" />
 
<script language="javascript" type="text/javascript">
var min=10;
var max=13;
function increaseFontSize() {
   var p = document.getElementsByTagName('form');
   for(i=0;i<p.length;i++) {
      if(p[i].style.fontSize) {
         var s = parseInt(p[i].style.fontSize.replace("px",""));
      } else {
         var s = 12;
      }
      if(s!=max) {
         s += 1;
      }
      p[i].style.fontSize = s+"px"
   }
}
function decreaseFontSize() {
   var p = document.getElementsByTagName('form');
   for(i=0;i<p.length;i++) {
      if(p[i].style.fontSize) {
         var s = parseInt(p[i].style.fontSize.replace("px",""));
      } else {
         var s = 12;
      }
      if(s!=min) {
         s -= 1;
      }
      p[i].style.fontSize = s+"px"
   }   
}
 
function callPrint()
{
    //window.print();
        //var win = window.open('/Print.htm','', 'letf=0,top=0,width=500,height=200,toolbar=0,scrollbars=1,status=0,resizable=1')
         location.href = "/Print.htm";
}
 
function EmailToFriend()
{       
        var mailURL;
        mailURL = window.document.location.toString();
        //window.open("/frmEmailPage.aspx?page="+mailURL,"Email","menubar=no,height=320,width=380,scrollbars=yes")
    location.href = "/frmEmailPage.aspx";
 
 
function onchangeSel(ctl)
{    
    //window.open(ctl.value) 
     location.href = ctl.value;
}
 
    function ClearSearchText()
    {    
        var SpeedSearch = 'Header1_txtSpeedSearch';
        document.getElementById(SpeedSearch).value="";
        document.getElementById(SpeedSearch).focus();        
    }
        
    function callSearchout()
    {
        
       var SpeedSearch = 'Header1_txtSpeedSearch';
     
       if(document.getElementById(SpeedSearch).value == "")
       { 
           document.getElementById(SpeedSearch).value="Search Text";
               
       }
    }
    
   function SpeedSearch()
   {
   
        var SpeedSearch = 'Header1_txtSpeedSearch';
        
        if ((document.getElementById(SpeedSearch).value == "") || (document.getElementById(SpeedSearch).value == "Search Text"))
            {
                document.getElementById(SpeedSearch).value = "";
                alert("Please enter keyword to search.");
                document.getElementById(SpeedSearch).focus();         
                return false;
            }
   }
   
   function TagSearch()
   {
   
        var TagSearch = 'Header1_txtSearchContent';
        
        if ((document.getElementById(TagSearch).value == "") || (document.getElementById(TagSearch).value == "Keyword Search"))
            {
                document.getElementById(TagSearch).value = "";
                alert("Please enter keyword to search.");
                document.getElementById(TagSearch).focus();           
                return false;
            }
   }
   
   
        function txt_onfocus(ctl)
        {   
             if(ctl.value=="Keyword Search")
                {
                    ctl.value="";
                                         
                }                         
            return false;
        }
        
        function txt_onblur(ctl)
        {           
                if(ctl.value=="")
                    ctl.value="Keyword Search";
         
            return false;
        }
        
        
        function txt_KeyPress(e)
        {  
                 var key;
                 if(window.event)
                      key = window.event.keyCode;     //IE
                 else
                      key = e.which;     //firefox
            
             if (key == 13)
             {        
               var ibmBtnId = 'Header1_imgBtnSearch';
                         
                var btn=document.getElementById(ibmBtnId); 
                if (btn != null)
                { 
                    btn.click();
                    event.keyCode = 0
                }                      
             }
        }
 
</script>
 
<script language="JavaScript">
<script language="JavaScript1.2">
 
if (document.all||document.getElementById)
 
document.body.style.background="url('logo1.jpg') white center no-repeat fixed"
 
</script>
function total_expenses() {
    // reteriving all the values from textboxes and parsing string to Float
    var txtBx1 = parseFloat(document.getElementById('textField01').value);
    var txtBx2 = parseFloat(document.getElementById('textField02').value);
    var txtBx3 = parseFloat(document.getElementById('textField03').value);
    var txtBx4 = parseFloat(document.getElementById('textField04').value);
    var txtBx5 = parseFloat(document.getElementById('textField05').value);
    var txtBx6 = parseFloat(document.getElementById('textField06').value);
    var txtBx7 = parseFloat(document.getElementById('textField07').value);
    // Storing total
    var totalVal = txtBx1 + txtBx2 + txtBx3 + txtBx4 + txtBx5 + txtBx6 + txtBx7;
    // converting numeric to string
    var strttl = totalVal + "";
    // Reformatting the total value
    document.getElementById('textField08').value = ReFrtFld(strttl);
     estimated_tax_savings();
}
 
//reformat to 0.00 format
function ReFrtFld(mystring) {
    var num;
    // using regular expression checking for numeric value upto two decimals.
    if (mystring.match(/^\d+$|^\d+\.\d{1}$/)) {
        num = parseFloat(mystring).toFixed(2);
        return num;
    } else {
        return mystring;
    }
 
}
 


<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
    <asp:Panel ID="panelContent" GroupingText="ContentPage Controls" runat="server">
        <asp:TextBox ID="txtContent" runat="server"></asp:TextBox>
        <asp:Button ID="btnContent" runat="server" Text="Button" OnClientClick="Populate();" />
    </asp:Panel>
    <script type="text/javascript" language="javascript">
        function Populate() {
            {
                document.getElementById('<%=txtContent.ClientID%>').value = "Hi";               
            }
        }
    </script>
</asp:Content>
Call JavaScript from Content Page
Here are some common scenarios of executing JavaScript from a Content Page.
1. Create a JavaScript function on the fly and call the JavaScript function in the Content Page Page_Load() event
C#
    protected void Page_Load(object sender, EventArgs e)
    {       
        const string someScript = "alertMe";
        if (!ClientScript.IsStartupScriptRegistered(this.GetType(), someScript))
        {
            ClientScript.RegisterStartupScript(this.GetType(),
                someScript, "alert('I was called from Content page!')", true);
        }
    }
VB.NET
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Dim someScript As String = "alertMe"
        If (Not ClientScript.IsStartupScriptRegistered(Me.GetType(), someScript)) Then
            ClientScript.RegisterStartupScript(Me.GetType(), someScript, "alert('I was called from Content page!')", True)
        End If
    End Sub
2. Call a JavaScript function declared in a .js file from the Content Page
If you have a .js file and want to call the function from your Content Page, then here’s how to do so.
Let’s create a .js file called TestScript.js and add the following function in the .js file.
function insideJS() {
    alert('Inside .js');
}
Assuming that your .js file is kept in a Script folder, reference the file in your MasterPage in the following manner.
<head runat="server">
    <title></title>
    <script src="Scripts/TestScript.js" type="text/javascript"></script>
...
Now in your Content Page(in our case Default.aspx.cs or .vb), call the JavaScript function on the Page_Load:
C#

    protected void Page_Load(object sender, EventArgs e)
    {       
        if (!Master.Page.ClientScript.IsStartupScriptRegistered("alert"))
        {
            Master.Page.ClientScript.RegisterStartupScript
                (this.GetType(), "alert", "insideJS();", true);
        }
    }

VB.NET
      Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
            If (Not Master.Page.ClientScript.IsStartupScriptRegistered("alert")) Then
                  Master.Page.ClientScript.RegisterStartupScript (Me.GetType(), "alert", "insideJS();", True)
            End If
      End Sub
3. Referencing the .js file from a Content Page instead of the Master page
The approach shown above in Tip 2 works well, however this approach would add a reference to the .js file for every page in the application (since we are adding the .js in the Master Page). If you want to avoid this approach, then remove the reference added to the .js file in Tip 2 in the Master Page. Now add a reference to the .js file from the Content Page using the ‘RegisterClientScriptInclude’ as shown below:
C#
    protected void Page_Load(object sender, EventArgs e)
    {
        Page.ClientScript.RegisterClientScriptInclude("selective", ResolveUrl(@"Scripts\TestScript.js"));
        if (!Master.Page.ClientScript.IsStartupScriptRegistered("alert"))
        {
            Master.Page.ClientScript.RegisterStartupScript
                (this.GetType(), "alert", "insideJS();", true);
        }
    }
VB.NET
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
        Page.ClientScript.RegisterClientScriptInclude("selective", ResolveUrl("Scripts\TestScript.js"))
        If (Not Master.Page.ClientScript.IsStartupScriptRegistered("alert")) Then
            Master.Page.ClientScript.RegisterStartupScript(Me.GetType(), "alert", "insideJS();", True)
        End If
    End Sub
Using this approach, we can avoid referencing the .js file for every content page.
Note: This approach adds the JavaScript reference inside the <body>tag of the page.
4. Declare JavaScript inside the Content page and execute it
If you are looking out to declare JavaScript inside the Content Page, then here’s how to do so. Add the following markup inside the Content page (in our case Default.aspx)
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
    <asp:Panel ID="panelContent" GroupingText="ContentPage Controls" runat="server">
        <asp:TextBox ID="txtContent" runat="server"></asp:TextBox>
        <asp:Button ID="btnContent" runat="server" Text="Button" OnClientClick="Populate();" />
    </asp:Panel>
    <script type="text/javascript" language="javascript">
        function Populate() {
            {
                document.getElementById('<%=txtContent.ClientID%>').value = "Hi";               
            }
        }
    </script>
</asp:Content>
The markup shown above populates the textbox with some text on a button click.
5. Accessing a Control on the Master Page From a ContentPage using JavaScript
In our previous article, we saw how in Tip 5 To access a control on the ContentPage From a Master Page using JavaScript. In this tip, we will see how to access a control kept on the MasterPage from a ContentPage. Do the following:
We have added a textbox control to the <body> of the MasterPage  as shown below:
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Panel ID="panelMaster" GroupingText="MasterPage controls" runat="server">      
            <asp:TextBox ID="txtMaster" runat="server"></asp:TextBox>
            <br />
        </asp:Panel>
        <asp:ContentPlaceHolder id="ContentPlaceHolder1" runat="server">
       
        </asp:ContentPlaceHolder>
    </div>
    </form>
</body>
We will now access this TextBox ‘txtMaster’ in the ContentPage using JavaScript
To do so, go to the Content page (Default.aspx) and add the following line below the <Page> directive to register the MasterPage
<%@ Page Title="" Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
...
<%@ MasterType VirtualPath="~/MasterPage.master" %>
...
Now in the code behind of Default.aspx.cs or .vb, access the MasterPage control in the following manner
C#
   protected void Page_Load(object sender, EventArgs e)
    {
        TextBox tb = (TextBox)Master.FindControl("txtMaster");
        string val = tb.ClientID;
        string script = @"<script>
        function PopulateMaster() {
            document.getElementById('" + val + @"').value = 'Via Content Page. Love dotnetcurry';               
        }
        PopulateMaster();
        </script>";
        if (!Page.ClientScript.IsStartupScriptRegistered("Mast"))
        {
            Page.ClientScript.RegisterStartupScript(this.GetType(),
                "Mast", script);
        }

    }
VB.NET
   Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
            Dim tb As TextBox = CType(Master.FindControl("txtMaster"), TextBox)
            Dim val As String = tb.ClientID
            Dim script As String = "<script>" & ControlChars.CrLf & "        function PopulateMaster() {" & ControlChars.CrLf & "            document.getElementById('" & val & "').value = 'Via Content Page. Love dotnetcurry.com';                " & ControlChars.CrLf & "        }" & ControlChars.CrLf & "        PopulateMaster();" & ControlChars.CrLf & "        </script>"
            If (Not Page.ClientScript.IsStartupScriptRegistered("Mast")) Then
                  Page.ClientScript.RegisterStartupScript(Me.GetType(), "Mast", script)
            End If

   End Sub
Observe how we have used the RegisterStartupScript instead of RegisterClientScriptBlock. The main difference is that the 'RegisterStartupScript' method places the JavaScript at the bottom of the ASP.NET page right before the closing </form> element whereas the 'RegisterClientScriptBlock' method places the JavaScript directly after the opening <form> element in the page. Had we used the 'RegisterClientScriptBlock', the browser would have executed the JavaScript before the text box is on the page. Therefore, the JavaScript would not have been able to find a ‘txtMaster’ and would give a control not found error. Understanding this simple difference between the two methods can save you hours of work!
6. Call JavaScript function from an ASP.NET AJAX enabled Content Page
If your content page is wrapped in an ASP.NET AJAX UpdatePanel, then you cannot use the ClientScript.RegisterStartupScript to call a JavaScript function during a partial-page postback. Instead, use the ScriptManager.RegisterStartupScript() method.
C#
    protected void Page_Load(object sender, EventArgs e)
    {
        System.Text.StringBuilder sb = new System.Text.StringBuilder();
        sb.Append(@"<script language='javascript'>");
        sb.Append(@"alert('I love dotnetcurry.com');");       
        sb.Append(@"</script>");

        ScriptManager.RegisterStartupScript(this, this.GetType(), "ajax", sb.ToString(), false);

    }
VB.NET
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
        Dim sb As New System.Text.StringBuilder()
        sb.Append("<script language='javascript'>")
        sb.Append("alert('I love dotnetcurry');")
        sb.Append("</script>")

        ScriptManager.RegisterStartupScript(Me, Me.GetType(), "ajax", sb.ToString(), False)

    End Sub
Observe that the last parameter for RegisterStartupScript() is set to 'false'. This means that the <script> tags will not be added automatically. Since we have already inserted the <script> tags while creating the script in the StringBuilder, we do not need to insert them now.
  function Validate() {
            var Flag = false;
            //alert(document.getElementByID('<%=UC_Districts.ClientID %>'));           
             var DistrictId =document.getElementById('ctl00_ContentPlaceHolder1_UC_Districts_ddl_Districts');
            var CropId = document.getElementById('<%=ddl_CropTypes.ClientID%>');
            var Production = document.getElementById('<%=txt_Production.ClientID%>');
            var Source = document.getElementById('<%=txt_Source.ClientID%>');
            if (DistrictId.value > 0) {
                if (CropId.value > 0) {
                    if (Production.value != "") {
                        if (Source.value != "") {
                            Flag = true;
                        }
                        else {
                            alert('Enter Source');
                            Flag = false;
                        }

                    }
                    else {
                        alert('Enter Production');
                        Flag = false;
                    }

                }
                else {
                    alert('Select Crop');
                    Flag = false;
                }
            }
            else {
                alert('Select District');
                Flag = false;
            }
           
            if (!Flag)
                return false;
            else
                return true;
        }
    </script>








No comments:

Post a Comment