Partager via


Adding JScript Code to an HTML Page

To add JScript code to an HTML page, enclose the script within a pair of <SCRIPT> tags, using either the TYPE attribute or the LANGUAGE attribute to specify the scripting language. You can place JScript code blocks anywhere on an HTML page. However, it is a good practice to put all general-purpose scripting code (that is, script that is not tied to a particular form control) in the HEAD section. This ensures that script will already have been read and decoded before it is called from the body of the HTML page.

The following JScript code example validates user-supplied data before sending a form.

<SCRIPT TYPE="text/JScript"> 
//Or: <SCRIPT LANGUAGE="JScript" 
function ValidateForm(eForm)
{
  // --------------------------------------------
  // Check for a blank name.
  // --------------------------------------------
  if ("" == eForm.txtName.value)
  {
    window.alert("Please enter your name.    ");
    return false;
  }
  // --------------------------------------------
  // Check for a blank password.
  // --------------------------------------------
  if ("" == eForm.txtPassword.value)
  {
    window.alert("Please enter your password.    ");
    return false;
  }
  // --------------------------------------------
  // Check for an unselected size option.
  // --------------------------------------------
  else if (0 == eForm.selSize.selectedIndex)
  {
    window.alert("Please select a size.    ");
    return false;
  }
  else
  {
  // --------------------------------------------
  // Check for no selected Crust radio buttons.
  // --------------------------------------------
    var bCrustChecked = false;
    for (var i=0;i<eForm.radCrust.length;i++)
    {
      if (eForm.radCrust[i].checked)
      {
        bCrustChecked = true;
        var sCrust = eForm.radCrust[i].value;
        break;
      }
    }
    if (!bCrustChecked)
    {
      window.alert("Please select a crust type.    ");
      return false;
    }
  }
  window.alert("All is well. Submitting form...    ");
  return true;
}
</SCRIPT>

For this script to actually prevent an invalid page from being sent, you would also need to hook up an event handler function, such as onsubmit, explicitly requesting the return value from the JScript function, as follows.

<form name="form1" onsubmit="return ValidateForm(this);">

See Also

JScript 5.5

 Last updated on Thursday, April 08, 2004

© 1992-2003 Microsoft Corporation. All rights reserved.