button

JavaScript Button Coding a JavaScript button by yourself JavaScript buttons can give nice effects to your web page. If done properly, JavaScript buttons give very impressive look and feel. This article shows you the creation of a JavaScript button in simple steps. The working of a JavaScript Button The JavaScript button effects are created using images. The JavaScript button requires three images for the different stages (normal, active and clicked). When the user moves the mouse over the image, the image is switched to the ‘active’ image. When the user clicks the image, the image is switched to ‘clicked’ image This in effect creates the feeling of a button. JavaScript buttons are also known as Mouse over buttons. The image object In order to display an image, the HTML code is: javascript button To refer this image in the JavaScript, you need to give a name to the image using the ‘name’ attribute. javascript button The HTML code for the image is ready. Now our button will look as shown below: javascript button Accessing the Image From JavaScript Once the image object is inserted in the HTML page, you can access it using the name you have given. var myimgobj = document.images["jsbutton"]; There are many properties for the JavaScript image object. However, the property that we are interested is the ’src’ property. This property contains the image file name. So if you change the src property of the image object to another file, the image will change. Handling the Mouse-Over Event We need to change the image when the user moves the mouse over the image. So we have to handle the event that the browser sends when the user moves the mouse over the image. However, the image object does not support onMouseOver event. The workaround is to include the image within the anchor ( ) tag and handle the mouse over event. We need to correct the HTML for the image as javascript button We have defined the handler for the mouse over event as changeImage() function. Now we need to define this function. function changeImage() { document.images["jsbutton"].src=”buyit15u.jpg”; return true; } The function (that we defined as the mouse over handler) just changes the src attribute to another image file. The example is available here: JavaScript button Example 1 Click the link above and the code working. Move the mouse over the button; the image changes. Handling the Mouse-Out Event But as you can see, even when you move the mouse out, the image is not changing back to the old image. For changing back to the old image, we need to handle the onMouseOut event also. javascript button The changeImageBack() event handler has to take care of changing the image when the user moves the mouse cursor out of the image. The modified code is as shown below: function changeImage() { document.images["jsbutton"].src=”buyit15u.jpg”; return true; } function changeImageBack() { document.images["jsbutton"].src=”buyit15.jpg”; return true; } See the modified example file: JavaScript button Example 2 Handling the Mouse Click Event You may also want to change the image when the button is pressed. The Mouse Down and the Mouse Up messages are to be handled for creating this effect. The code below handles the Mouse up and Mouse down messages also: javascript button function changeImage() { document.images["jsbutton"].src=”buyit15u.jpg”; return true; } function changeImageBack() { document.images["jsbutton"].src=”buyit15.jpg”; return true; } function handleMDown() { document.images["jsbutton"].src=”buyit15d.jpg”; return true; } function handleMUp() { changeImage(); return true; } The example file is here: JavaScript button Example 3 Navigating to Another Page You can give the URL in the ‘href’ attribute of the anchor ( ) tag to navigate to that page when the user clicks the button. For example: Image Pre-fetching Image pre-fetching is a technique to make the browser load and decode the image early. Image pre-fetching could be used to create smooth image transition effects. You might have noticed that for the first time the button transition is not smooth, in the examples above. The solution is to make the browser load the image and keep it in cache. You can use the Image() JavaScript object to make the browser pre-fetch the images. The javascript code for creating the image object goes like this: upimage = new Image(); upimage.src=”buyit15u.jpg”; downimage = new Image(); downimage.src=”buyit15d.jpg” The image objects are created while loading the page. This forces the browser to load the images from the site and decode it. The button code we developed, with image pre-fetching support, is given below: javascript button upImage = new Image(); upImage.src=”buyit15u.jpg”; downImage = new Image(); downImage.src=”buyit15d.jpg” normalImage = new Image(); normalImage.src=”buyit15.jpg”; function changeImage() { document.images["jsbutton"].src= upImage.src; return true; } function changeImageBack() { document.images["jsbutton"].src = normalImage.src; return true; } function handleMDown() { document.images["jsbutton"].src = downImage.src; return true; } function handleMUp() { changeImage(); return true; }

vAlidasi Form

1.Include gen_validatorv2.js in your html file just before closing the HEAD tag

<script language="JavaScript" src="gen_validatorv2.js" type="text/javascript"></script>
</head>

2. Just after defining your form, Create a form validator object passing the name of the form

<FORM name='myform' action="">
<!----Your input fields go here -->
</FORM>
<SCRIPT language="JavaScript">
var frmvalidator = new Validator("myform");
....

3. Now add the validations required

frmvalidator.addValidation("FirstName","alpha");

the first argument is the name of the field and the second argument is the validation descriptor, which specifies the type of validation to be performed.
You can add any number of validations. The list of validation descriptors are provided at the end of the documentation.
The optional third argument is the error string to be displayed if the validation fails.

frmvalidator.addValidation("FirstName","alpha");
frmvalidator.addValidation("FirstName","req","Please enter your First Name");
frmvalidator.addValidation("FirstName","maxlen=20",
"Max length for FirstName is 20");

4. Similarly, add validations for the fields where validation is required.
That’s it! You are ready to go.

Example

The example below will make the idea clearer
<form action="" name="myform" >
<table cellspacing="2" cellpadding="2" border="0">
<tr>
<td align="right">First Name</td>
<td><input type="text" name="FirstName"></td>
</tr>
<tr>
<td align="right">Last Name</td>
<td><input type="text" name="LastName"></td>
</tr>
<tr>
<td align="right">EMail</td>
<td><input type="text" name="Email"></td>
</tr>
<tr>
<td align="right">Phone</td>
<td><input type="text" name="Phone"></td>
</tr>
<tr>
<td align="right">Address</td>
<td><textarea cols="20" rows="5" name="Address"></textarea></td>
</tr>
<tr>
<td align="right">Country</td>
<td>
<SELECT name="Country">
<option value="" selected>[choose yours]
<option value="008">Albania
<option value="012">Algeria
<option value="016">American Samoa
<option value="020">Andorra
<option value="024">Angola
<option value="660">Anguilla
<option value="010">Antarctica
<option value="028">Antigua And Barbuda
<option value="032">Argentina
<option value="051">Armenia
<option value="533">Aruba
</SELECT>
</td>
</tr>
<tr>
<td align="right"></td>
<td><input type="submit" value="Submit"></td>
</tr>
</table>
</form>
<script language="JavaScript" type="text/javascript">
var frmvalidator = new Validator("myform");
frmvalidator.addValidation("FirstName","req","Please enter your First Name");
frmvalidator.addValidation("FirstName","maxlen=20",
"Max length for FirstName is 20");
frmvalidator.addValidation("FirstName","alpha");

frmvalidator.addValidation(“LastName”,”req”);
frmvalidator.addValidation(“LastName”,”maxlen=20″);

frmvalidator.addValidation(“Email”,”maxlen=50″);
frmvalidator.addValidation(“Email”,”req”);
frmvalidator.addValidation(“Email”,”email”);

frmvalidator.addValidation(“Phone”,”maxlen=50″);
frmvalidator.addValidation(“Phone”,”numeric”);

frmvalidator.addValidation(“Address”,”maxlen=50″);
frmvalidator.addValidation(“Country”,”dontselect=0″);
</script>

Some Additional Notes

  • The form validators should be created only after defining the HTML form (only after the </form> tag. )
  • Your form should have a distinguished name. If there are more than one form in the same page, you can add validators for each of them. The names of the forms and the validators should not clash.
  • You can’t use the javascript onsubmit event of the form if it you are using this validator script. It is because the validator script automatically overrides the onsubmit event. If you want to add a custom validation, see the section below
  • Adding Custom Validation

    If you want to add a custom validation, which is not provided by the validation descriptors, you can do so. Here are the steps:

  • Create a javascript function which returns true or false depending on the validation.
    function DoCustomValidation()
    {
    var frm = document.forms["myform"];
    if(frm.pwd1.value != frm.pwd2.value)
    {
    alert('The Password and verified password does not match!');
    return false;
    }
    else
    {
    return true;
    }
    }
  • Associate the validation function with the validator object.
    frmvalidator.setAddnlValidationFunction("DoCustomValidation");
  • The custom validation function will be called automatically after other validations.

    If you want to do more than one custom validations, you can do all those validations in the same function.

    function DoCustomValidation()
    {
    var frm = document.forms["myform"];
    if(false == DoMyValidationOne())
    {
    alert('Validation One Failed!');
    return false;
    }
    else
    if(false == DoMyValidationTwo())
    {
    alert('Validation Two Failed!');
    return false;
    }
    else
    {
    return true;
    }
    }

    where DoMyValidationOne() and DoMyValidationTwo() are custom functions for validation.

    Clear All Validations

    In some dynamically programmed pages, it may be required to change the validations in the form at run time. For such cases, a function is included which clears all validations in the validator object.

    frmvalidator.clearAllValidations();

    this function call clears all validations you set.
    You will not need this method in most cases.

    Table of Validation Descriptors

    required
    req
    The field should not be empty
    maxlen=???
    maxlength=???
    checks the length entered data to the maximum. For example, if the maximum size permitted is 25, give the validation descriptor as “maxlen=25″
    minlen=???
    minlength=???
    checks the length of the entered string to the required minimum. example “minlen=5″
    alphanumeric /
    alnum
    Check the data if it contains any other characters other than alphabetic or numeric characters
    num
    numeric
    Check numeric data
    alpha
    alphabetic
    Check alphabetic data.
    email The field is an email field and verify the validity of the data.
    lt=???
    lessthan=???
    Verify the data to be less than the value passed. Valid only for numeric fields.
    example: if the value should be less than 1000 give validation description as “lt=1000″
    gt=???
    greaterthan=???
    Verify the data to be greater than the value passed. Valid only for numeric fields.
    example: if the value should be greater than 10 give validation description as “gt=10″
    regexp=??? Check with a regular expression the value should match the regular expression.
    example: “regexp=^[A-Za-z]{1,20}$” allow up to 20 alphabetic characters.
    dontselect=?? This validation descriptor is valid only for select input items (lists) Normally, the select list boxes will have one item saying ‘Select One’ or some thing like that. The user should select an option other than this option. If the index of this option is 0, the validation description should be “dontselect=0″

    <!– 21 Oct 2006 Blocking link to simfatic.com

    NOTE: Simfatic Forms contains still more number of validations (comparison validations, check box & radio button validations and more)
    You can have conditional validations too ( validate only if a condition is met ). Using Simfatic Forms, you can add validations to your forms without writing a single line of code!Using Simfatic Forms you can design generate, install and maintain web forms painlessly. Click here for more information

    –>

    Example Page

    See the JavaScript form validation example here

    window.close method

    Sample Code for window.close()

    <html>
    <head>
    <title>JavaScript Window Close Example </title>
    </head>
    <SCRIPT language="JavaScript1.2">
    function popuponclick()
    {
    my_window = window.open("",
    "mywindow","status=1,width=350,height=150");
    my_window.document.write('<H1>The Popup Window</H1>');
    }
    function closepopup()
    {
    if(false == my_window.closed)
    {
    my_window.close ();
    }
    else
    {
    alert(‘Window already closed!’);
    }
    }
    </SCRIPT>
    <body>
    <P>
    <A href="javascript: popuponclick()">Open Popup Window</A>
    </P>
    <P>
    <A href="javascript: closepopup()">Close the Popup Window</A>
    </P>
    </body>
    </html>

    use something like this for waiting # sec before loading url link.

    <BODY>
    <script type=text/javascript>
    function goNow() {
    document.location=_l;
    }
    function setUp() {
    setTimeout(“goNow()”,_time); // 3 seconds delay
    }
    var _l = “http://www.urlhere.com/”;
    var _time = 3000; // msecs.
    onLoad=’setUp()’;
    </script>

    </BODY>

    referring info at this page:
    http://www.js-examples.com/example/?ex=272

    The action page (after processing the form) should generate html like this:

    <html>
    <head>
    <script type=”text/javascript“>
    if (window.opener && !window.opener.closed) window.opener.location.href=”successpage.htm”;
    window.close();
    </script>
    </head>
    <body>
    </body>
    </html>

    But I prefer to display the success page in the popup itself:

    <html>
    <head>
    </head>
    <body onload=”setTimeout(‘window.close()’, 3000)”>
    The page has been successfully processed.
    <form>
    <input type=”button” value=”Close” onclick=”window.close()”>
    </form>
    </body>
    </html>

    If you want to do something in the main window (like reload it or navigate to another url)

    <html>
    <head>
    <script type=”text/javascript“>
    function doClose(){
    if (window.opener && !window.opener.closed) {
    window.opener.location.reload();
    //or
    //window.opener.location.href=”somepage.htm”;
    }
    window.close();
    }
    </script>
    </head>
    <body onload=”setTimeout(‘doClose()’, 3000)”>
    The page has been successfully processed.
    <form>
    <input type=”button” value=”Close” onclick=”doClose()”>
    </form>
    </body>
    </html>

    I used the following code on the success page, works like a charm. It even recognized that the referring window was the iframe from the parent page and loaded the successdefault.html into the iframe as it should Thanks again!

    <head>

    <script type=”text/javascript“>
    function doClose(){
    if (window.opener && !window.opener.closed) {
    //window.opener.location.reload();
    //or
    window.opener.location.href=”successdefault.html”;
    }
    window.close();
    }
    </script>

    </head>

    <body onLoad=doClose()>

    The action page (after processing the form) should generate html like this:

    <html>
    <head>
    <script type=”text/javascript“>
    if (window.opener && !window.opener.closed) window.opener.location.href=”successpage.htm”;
    window.close();
    </script>
    </head>
    <body>
    </body>
    </html>

    But I prefer to display the success page in the popup itself:

    <html>
    <head>
    </head>
    <body onload=”setTimeout(‘window.close()’, 3000)”>
    The page has been successfully processed.
    <form>
    <input type=”button” value=”Close” onclick=”window.close()”>
    </form>
    </body>
    </html>

    If you want to do something in the main window (like reload it or navigate to another url)

    <html>
    <head>
    <script type=”text/javascript“>
    function doClose(){
    if (window.opener && !window.opener.closed) {
    window.opener.location.reload();

    function DoSomething()
    {
    var outW = window.open(“”, “newwin”, “top=250, left=250, height=150, width=300″);
    outW.document.write(“<HTML>”)
    outW.document.write(“<TITLE>Confirmation</TITLE>”);
    outW.document.write(“<body onload=’setTimeout(‘window.close()”, 5000>”);
    outW.document.write(“<font color=#0000CC>”);
    outW.document.write(“<div align=center><strong>Thank You”);
    outW.document.write(“<P>Your Information has been received.</P></strong></div></font>”);
    outW.document.write(“</body></HTML>”);
    window.close();
    //outW= window.setTimeout(document.close(), 2000);
    }
    //or
    //window.opener.location.href=”somepage.htm”;
    }
    window.close();
    }
    </script>
    </head>
    <body onload=”setTimeout(‘doClose()’, 3000)”>
    The page has been successfully processed.
    <form>
    <input type=”button” value=”Close” onclick=”doClose()”>
    </form>
    </body>
    </html>

    You have nested quotes and invalid <body> tag.

    function DoSomething()
    {
    var outW = window.open(“”, “newwin”, “top=250, left=250, height=150, width=300″);
    outW.document.write(“<HTML>”)
    outW.document.write(“<TITLE>Confirmation</TITLE>”);
    outW.document.write(“<body onload=\”setTimeout(‘window.close()’, 5000)\”>”;
    outW.document.write(“<font color=#0000CC>”);
    outW.document.write(“<div align=center><strong>Thank You”);
    outW.document.write(“<P>Your Information has been received.</P></strong></div></font>”);
    outW.document.write(“</body></HTML>”);
    outW.document.close();
    window.close();
    }