JavaScript DHTML/Form Control/Button

Материал из Web эксперт
Версия от 07:21, 26 мая 2010; Admin (обсуждение | вклад) (1 версия)
(разн.) ← Предыдущая | Текущая версия (разн.) | Следующая → (разн.)
Перейти к: навигация, поиск

Animating Buttons with JavaScript

  
<html>
<head>
  <title>JavaScript Unleashed</title>
  <script type="text/javascript" language="JavaScript1.1">
  <!--
   
    // Define image objects
    var prevBtnOff = new Image(42, 52);
    prevBtnOff.src = "http://www.wbex.ru/style/logo.png";
   
    var prevBtnOn =  new Image(42, 52);
    prevBtnOn.src = "http://www.wbex.ru/style/logoRed.png";
   
    var nextBtnOff = new Image(42, 52);
    nextBtnOff.src = "http://www.wbex.ru/style/logo.png";
   
    var nextBtnOn =  new Image(42, 52);
    nextBtnOn.src = "http://www.wbex.ru/style/logoRed.png";
   
    // Changes image being displayed.
    function highlightButton(placeholder, imageObject) {
      document.images[placeholder].src = eval(imageObject + ".src")
    }
   
  //-->
  </script>
</head>
<body background="./aiback.gif">
  <center>
    <a href="javascript:history.back()"
       onmouseover="highlightButton("Prev","prevBtnOn");
                    window.status="Previous";
                    return true;"
       onmouseout="highlightButton("Prev","prevBtnOff");
                   window.status="";
                   return true;">
      <img src="./prev_off.gif" border="0" width="52" height="42" name="Prev">
    </a>
    <a href="javascript:history.forward()"
       onmouseover="highlightButton("Next","nextBtnOn");
                    window.status="Next";
                    return true;"
       onmouseout="highlightButton("Next","nextBtnOff");
                    window.status="";
                    return true;">
      <img src="./next_off.gif" border="0" width="52" height="42" name="Next">
    </a>
  </center>
</body>
</html>



Assign JavaScript function to button onClick event handler

  
<HTML>
<HEAD>
<SCRIPT language="JavaScript">
function send_alerts()
{
    window.alert("Hi!");
}
</SCRIPT>
</HEAD>
<BODY>
<FORM>
<INPUT type="button" value="Click Me" onClick="send_alerts();">
</FORM>
</BODY>
</HTML>



Button and Check Box Event Handling

  
<HTML>
<HEAD>
<TITLE>Button and Check Box Events</TITLE>
<SCRIPT LANGUAGE="JavaScript"><!--
function showResults() {
 var resultMsg=""
 if(document.survey.age[0].checked) resultMsg+="under 30, "
 if(document.survey.age[1].checked) resultMsg+="between 30 and 60, "
 if(document.survey.age[2].checked) resultMsg+="over 60, "
 if(document.survey.sex[0].checked) resultMsg+="male, "
 if(document.survey.sex[1].checked) resultMsg+="female, "
 if(document.survey.reading.checked) resultMsg+="reading, "
 if(document.survey.eating.checked) resultMsg+="eating, "
 if(document.survey.sleeping.checked) resultMsg+="sleeping, "
 
 alert(resultMsg);
}
function upperCaseResults() {
 var newResults=document.survey.results.value
 alert(newResults.toUpperCase());
}
//--></SCRIPT>
</HEAD>
<BODY>
<FORM NAME="survey">
<H2 ALIGN="CENTER">Survey Form</H2>
<P><B>Age:</B>
<INPUT TYPE="RADIO" NAME="age" VALUE="under30" ONCLICK="showResults()">Under 30
<INPUT TYPE="RADIO" NAME="age" VALUE="30to60"  ONCLICK="showResults()">30 - 60
<INPUT TYPE="RADIO" NAME="age" VALUE="over60"  ONCLICK="showResults()">Over 60</P>
<P><B>Sex: </B>
<INPUT TYPE="RADIO" NAME="sex" VALUE="male" ONCLICK="showResults()">Male
<INPUT TYPE="RADIO" NAME="sex" VALUE="female" ONCLICK="showResults()">Female</P>
<P><B>Interests: </B>
<INPUT TYPE="CHECKBOX" NAME="reading" ONCLICK="showResults()"> Reading
<INPUT TYPE="CHECKBOX" NAME="eating"  ONCLICK="showResults()"> Eating
<INPUT TYPE="CHECKBOX" NAME="sleeping" ONCLICK="showResults()"> Sleeping</P>
<P>
<INPUT TYPE="BUTTON" NAME="makeUpper" VALUE="To Upper Case" ONCLICK="upperCaseResults()"></P>
<P><B>Results: </B><INPUT TYPE="TEXT" NAME="results" SIZE="50"></P>
<INPUT TYPE="SUBMIT" NAME="submit" VALUE="Submit" ONCLICK="return confirm("Sure?")">
<INPUT TYPE="RESET" NAME="reset" ONCLICK="return confirm("Sure?")">
</FORM>
</BODY>
</HTML>



Button Click action

  
<HTML>
<BODY>
<FORM>
<INPUT type="button" value="Change Status!" onClick="window.status="Hey there!";">
<P>
<INPUT type="button" value="Clear Status!" onClick="window.status="";">
</FORM>
<P>
<A HREF="noplace" onMouseOver="window.location="http://www.wbex.ru";">No need to click this link.</A>
</BODY>
</HTML>



Button click to display dialog

  
/*
Examples From
JavaScript: The Definitive Guide, Fourth Edition
Legal matters: these files were created by David Flanagan, and are
Copyright (c) 2001 by David Flanagan.  You may use, study, modify, and
distribute them for any purpose.  Please note that these examples are
provided "as-is" and come with no warranty of any kind.
David Flanagan
*/
<form>
<input type="button"
       value="Click here" 
       onclick="alert("You clicked the button");">
</form>



Button "default Value" Example

  
    
<html>
<body>
<script language="JavaScript">
function function1() {
    var m = document.getElementById("myButton").defaultValue;
    alert("The value of this element is: "+"""+m+"""); 
} 
</script>
<input id="myButton" type="button" value="Click here" onclick="function1();">
</body>
</html>



Button disabled Example

  
    
<html>
<body>
<script>
    function function1() {
        document.all.myButton.disabled = true;
    }
    function function2() {
        document.all.myButton.disabled = false;
    }
</script>
<input id="myButton" type="button" value="Disable" onClick="function1();">
<input type="button" value="Enable" onClick="function2();">
</body>
</html>



Button On Click Action

  
 
<HTML>
<BODY>
<FORM>
<INPUT TYPE="button" value="Page Resource" onClick="window.location="http://www.wbex.ru"">
<P>
<INPUT TYPE="button" value="JavaScript City" onClick="window.location="http://www.wbex.ru"">
<P>
</FORM>
</BODY>
</HTML>



Button on click event

  
<HTML>
<BODY>
<A HREF="http://www.wbex.ru" onMouseOver="window.alert("over!");">wbex!</A> 
<P>
<FORM>
Phone Number: <INPUT type="text" size="25" onFocus="window.alert("on focus");">  
<BR>
Name: <INPUT type="text" size="25" onBlur="window.alert("focus lost");">
<BR>
E-mail Address: <INPUT type="text" size="25">
<P>
<INPUT type="button" value="Click Here." onClick="window.alert("on click")";>
</FORM>
</BODY>
</HTML>



Button parent Element

  
    
<html>
<body>
<form id="myF">
<input id="myButton" 
       type="button" value="Show my parent" onclick="function1();">
</form>
<script language="JavaScript">
    function function1() {
        var m = document.all.myButton.parentElement.id;
        alert("Parent element: <FORM>, ID = "+"""+m+"""); 
    } 
</script>



Button parentNode Example

  
    
<html>
<body>
<form id="myForm">
    <input id="myButton" type="button" value="Show parent node" onclick="function1();">
</form>
<script language="JavaScript">
function function1() {
    var m = document.all.myButton.parentNode.id;
    alert("Parent node: <form>, id = "+"""+m+"""); 
} 
</script>
</body>
</html>



Button Redirect

  
<html><head><title>Button Redirect</title>
<script language="javascript">
<!--
function NewPage() {
  document.location.href= "http://www.wbex.ru"
}
//-->
</script>
<body>
<input type="button" value="Link" onClick="NewPage()">
</body></html>



Button set Textfield value

  

<html>
<body>
<form name="quiz">
<input type="text" value="" name="sky">
<input type="hidden" value="blue" name="blue">
<input type="button" value="See Answer" onClick="document.quiz.sky.value=(document.quiz.blue.value)">
</form>
</body>
</html>



Button "sourceIndex" Example

  
    
<html>
<body>
<button onclick="alert(this.sourceIndex)">Source Index</button>
</body>
</html>



Button"s value

  
    
<html>
<body>
<form id="myForm">
    <table>
        <tr>
            <td>
                <input id="myButton" 
                       type="button" 
                       onClick="alert("This element value is:\n"+this.value);">
            </td>
            <td>
                <input id="myReset" 
                       type="reset" 
                       onClick="alert("This element value is:\n"+this.value);">
            </td>
            <td>
                <input id="mySubmit" 
                       type="submit" 
                       onClick="alert("This element value is:\n"+this.value);">
            </td>
        </tr>
    </table>
</form>
<script language="JavaScript">
    document.getElementById("myButton").value = "input type = "button"";
    document.getElementById("myReset").value="input type = "reset"";
    document.getElementById("mySubmit").value="input type = "submit"";
</script>
</body>
</html>



Button timeout

  
<html>
<head>
<title>Alarm Call Script</title>
<script language="JavaScript">
<!--
  var alarmId;
  function alarmFunc() {
    alert("ALARM CALL!");
  }
  function startTimeout(id) {
    var minutes = prompt("How many minutes?", 0);
    alarmId = setTimeout("alarmFunc()", minutes*60000);
}
//-->
</script>
</head>
<body>
<form>
<input type=button value="Start" onClick="startTimeout()">
<input type=button value="Cancel" onClick="clearTimeout(alarmId)">
</form>
</body>
</html>



Button to display the name of the form

  
<html>
<body>
<form name="myForm">
    The form"s name is: <input type="text" name="text1" size="20">
    <br>
    <br>
    <input type="button" value="Show the form"s name" 
                onClick="this.form.text1.value=this.form.name">
</form>
</body>
</html>



Button to display the names of all the elements in a form

  

<html>
<head>
<script type="text/javascript">
function showFormElements(theForm){
    str="Form Elements: "
    for (i=0; i<theForm.length; i++)
        str+=" \n " + theForm.elements[i].name
        alert(str)
    }
</script>
</head>
<body>
<form>
    First name: <input type="text" name="fname" size="20">
    <br>
    Last name: <input type="text" name="lname" size="20">
    <br>
    <br>
    <input type="button" name="button1" value="Display name of form elements"
            onClick="showFormElements(this.form)">
</form>
</body>
</html>



Create a button

  
<html>
<head>
<script type="text/javascript">
function show_alert(){
    alert("Hello World!")
    document.all("myButton").focus()
}
</script>
</head>
<body>
<form>
<input type="button" value="Click me!" name="myButton" onClick="show_alert()" />
</form>
</body>
</html>



Disable a Button

  
    
<html>
<body>
<button onclick="this.disabled="true"; alert(this.isDisabled);">Disable Me</button>
</body>
</html>



Form button on click event

  
<html>
<head>
<title>A Simple Page</title>
<script language="JavaScript">
function yourMessage(quote)
{
    alert(quote);
}
</script>
</head>
<body>
Click <input type="button" value="HERE" onClick="yourMessage("Hi!")"> A message!</p>
</body>
</html>



Form Button "type"

  
    
<html>
<body>
<input type="button" 
       value="type = "button""
       onClick="alert("&quot;"+this.type+"&quot;");">
<input type="reset" 
       value="type = "reset""
       onClick="alert("&quot;"+this.type+"&quot;");">
<input type="submit" 
       value="type = "submit""
       onClick="alert("&quot;"+this.type+"&quot;");">
</body>
</html>



Get form from form control (Button)

  
    
<html>
<body>
<script language="JavaScript">
function function1(form) {
    var elem = document.getElementById("myButton").form.id;
    alert(elem);
    return true; 
} 
</script>
<form id="myF">
<input id="myButton" 
       type="button" 
       value="Get ID of this control"s form" onClick="function1(this.form);">
</form>
</body>
</html>



HTML Form with onClick Code

  
<HTML>
<BODY>
<FORM> 
Enter Your Name:  <INPUT TYPE=text NAME=userName  VALUE="Name"> 
Enter Your Age:  <INPUT TYPE=text NAME=userAge  VALUE="12">
<INPUT TYPE=button VALUE="Check Age" 
onClick="var status = (userAge.value >= 21) ? "an adult" : "a minor"; 
alert(userName.value + " is " + status + ".");">
</FORM>
</BODY>
</HTML>



JavaScript Button action event

  
<HTML>
<HEAD>
<TITLE>Using Properties</TITLE></HEAD>
<BODY>
<H1>Using Properties</H1>
<FORM>
<P><INPUT TYPE="BUTTON" NAME="red" VALUE="Red"
 ONCLICK="document.bgColor="red""></P>
<P><INPUT TYPE="BUTTON" NAME="white" VALUE="White"
 ONCLICK="document.bgColor="white""></P>
<P><INPUT TYPE="BUTTON" NAME="blue" VALUE="Blue"
 ONCLICK="document.bgColor="blue""></P>
</FORM>
</BODY>
</HTML>



Methods and Properties of the Button Object

  
   Method
+-----------+----------+----------------------------------------------------+   
             blur()      Removes focus from the button.
+-----------+----------+----------------------------------------------------+    
             click()     Invokes a click event for that button.
+-----------+----------+----------------------------------------------------+    
             focus()     Applies focus to a button.
+-----------+----------+----------------------------------------------------+    
            handleEvent()Passes an event to the appropriate event handler 
                         associated with a button. 
+-----------+----------+----------------------------------------------------+    
 Property
+-----------+----------+----------------------------------------------------+    
             form        Returns the Form object of which the button is a member.
+-----------+----------+----------------------------------------------------+    
             name        Returns the string that is specified in the name 
                         attribute of the HTML <input> tag.
+-----------+----------+----------------------------------------------------+    
             type        Returns the string specified in the type 
                         attribute of the HTML <input> tag. This string is 
                         always button for the Button object.
+-----------+----------+----------------------------------------------------+    
             value       Returns the string that appears in the graphical 
                         representation of a button.



Open a new window with button

  

<html>
<head>
<script>
function startGame(){
  var stadium = window.open("http://www.wbex.ru", "asdf", "height=450,width=300");
  stadium.focus();
} 
</script>
</head>
<body>
<form>
<input type = "button" value = "start game" onClick = "startGame()">
</form>
</body>
</html>



Putting Script Directly in the onclick Event Handler

  
<html>
<head>
  <title>Page with Pushbutton</title>
</head>
<body>
  <form>
    <input type="SUBMIT" name="BUTTON1" value="PUSH" onclick="alert("pushed")">
  </form>
</body>
</html>



Roll over one of our images.

  
<html>
<head>
  <title>JavaScript Unleashed</title>
  <script type="text/javascript" language="JavaScript1.2">
  <!--
    var overImg = new Array();
    overImg[0] = new Image(24,24);
    overImg[1] = new Image(24,24);
   
    var defaultImg = new Array();
    defaultImg[0] = new Image(24,24);
    defaultImg[1] = new Image(24,24);
   
    overImg[0].src = "http://www.wbex.ru/style/logo.png";
    overImg[1].src = "http://www.wbex.ru/style/logoRed.png";
   
    defaultImg[0].src = "http://www.wbex.ru/style/logo.png";
    defaultImg[1].src = "http://www.wbex.ru/style/logoRed.png";
   
    function rollImage(img,type){
      switch(type){
        case "over":
          document.images[img].src = overImg[img].src;
          break;
        case "out":
          document.images[img].src = defaultImg[img].src;
          break;
      }
    }
  //-->
  </script>
</head>
<body>
  <table>
    <tr>
      <td align="center">
        <a href="javascript:void(0)"
             onmouseout="rollImage("0","out")"
             onmouseover="rollImage("0","over")">
          <img border="0" src="back.gif" width="24" height="24" alt="Back">
        </a>      </td>
      <td align="center">
        <a href="javascript:void(0)"
             onmouseout="rollImage("1","out")"
             onmouseover="rollImage("1","over")">
          <img border="0" src="forward.gif" width="24" height="24"
            alt="Forward"></a>
      </td>
    </tr>
  </table>
</body>
</html>



Running a Script from User Action

  
<HTML>
<HEAD>
<TITLE>An onClick script</TITLE>
<SCRIPT LANGUAGE="JavaScript">
<!--
function alertUser() {
    alert("Ouch!")
}
// -->
</SCRIPT>
</HEAD>
<BODY>
Here is some body text.
<FORM>
    <INPUT TYPE="text" NAME="entry">
    <INPUT TYPE="button" NAME="oneButton" VALUE="Press Me!" onClick="alertUser()">
</FORM>
</BODY>
</HTML>



Three Buttons Sharing One Function

  
<HTML>
<HEAD>
<TITLE>Button Click</TITLE>
<SCRIPT LANGUAGE="JavaScript">
function displayTeam(btn) {
    if (btn.value == "A") {alert("A")}
    if (btn.value == "R") {alert("R")}
    if (btn.value == "M") {alert("M")}
}
</SCRIPT>
</HEAD>
<BODY>
Click on your favorite half of a popular comedy team:<P>
<FORM>
<INPUT TYPE="button" VALUE="A" onClick="displayTeam(this)">
<INPUT TYPE="button" VALUE="R" onClick="displayTeam(this)">
<INPUT TYPE="button" VALUE="M" onClick="displayTeam(this)">
</FORM>
</BODY>
</HTML>



Toggle button with hand cursor and image

  
/*
Examples From
JavaScript: The Definitive Guide, Fourth Edition
Legal matters: these files were created by David Flanagan, and are
Copyright (c) 2001 by David Flanagan.  You may use, study, modify, and
distribute them for any purpose.  Please note that these examples are
provided "as-is" and come with no warranty of any kind.
David Flanagan
*/
<html>
<script language="JavaScript1.1">
// This is the constructor function for our new ToggleButton class.
// Calling it creates a ToggleButton object and outputs the required
// <a> and <img> tags into the specified document at the current location. 
// Therefore, don"t call it for the current document from an event handler.
// Arguments:
//    document: The Document object the buttons are be created in.
//    checked:  A boolean that says whether the button is initially checked.
//    label:    An optional string that specifies text to appear after the button.
//    onclick:  An optional function to be called when the toggle button is
//              clicked. It is passed a boolean indicating the new
//              state of the button. You can also pass a string, which is
//              be converted to a function that is passed a boolean argument
//              named "state".
function ToggleButton(document, checked, label, onclick)
{
    // The first time we are called (and only the first time), we have
    // to do some special stuff. First, now that the prototype object
    // is created, we can set up our methods. 
    // Second, we need to load the images we"ll be using.
    // Doing this gets the images in the cache for when we need them.
    if (!ToggleButton.prototype.over) {
        // Initialize the prototype object to create our methods.
        ToggleButton.prototype.over = _ToggleButton_over;
        ToggleButton.prototype.out = _ToggleButton_out;
        ToggleButton.prototype.click = _ToggleButton_click;
        // Now create an array of image objects, and assign URLs to them.
        // The URLs of the images are configurable and are stored in an
        // array property of the constructor function itself. They are
        // initialized below. Because of a bug in Netscape, we"ve got
        // to maintain references to these images, so we store the array
        // in a property of the constructor rather than using a local variable.
        ToggleButton.images = new Array(4);
        for(var i = 0; i < 4; i++) {
            ToggleButton.images[i] = new Image(ToggleButton.width,
                                               ToggleButton.height);
            ToggleButton.images[i].src = ToggleButton.imagenames[i];
        }
    }
    
    // Save some of the arguments we were passed.
    this.document = document;
    this.checked = checked;
    // Remember that the mouse is not currently on top of us.
    this.highlighted = false;
    // Save the onclick argument to be called when the button is clicked.
    // If it is not already a function, attempt to convert it
    // to a function that is passed a single argument, named state.
    this.onclick = onclick;
    if (typeof this.onclick == "string")
        this.onclick = new Function("state", this.onclick);
    // Figure out what entry in the document.images[] array the images
    // for this checkbox will be stored at.
    var index = document.images.length;
    // Now output the HTML code for this checkbox. Use <a> and <img> tags.
    // The event handlers we output here are confusing but crucial to the
    // operation of this class. The "_tb" property is defined below, as
    // are the over(), out(), and click() methods.
    document.write("&nbsp;<a href="about:blank" " +
      "onmouseover="document.images[" + index + "]._tb.over();return true;" "+
      "onmouseout="document.images[" + index + "]._tb.out()" "+
      "onclick="document.images[" + index + "]._tb.click(); return false;">");
    document.write("<img src="" + ToggleButton.imagenames[this.checked+0] +"""+
                   " width=" + ToggleButton.width +
                   " height=" + ToggleButton.height +
                   " border="0" hspace="0" vspace="0" align="absmiddle">");
    if (label) document.write(label);
    document.write("</a></br>");
    // Now that we"ve output the <img> tag, save a reference to the
    // Image object that it created in the ToggleButton object.
    this.image = document.images[index];
    // And also make a link in the other direction, from the Image object
    // to this ToggleButton object. Do this by defining a "_tb" property
    // in the Image object.
    this.image._tb = this;
}
// This becomes the over() method.
function _ToggleButton_over()
{
    // Change the image, and remember that we"re highlighted.
    this.image.src = ToggleButton.imagenames[this.checked + 2];
    this.highlighted = true;
}
// This becomes the out() method.
function _ToggleButton_out()
{
    // Change the image, and remember that we"re not highlighted.
    this.image.src = ToggleButton.imagenames[this.checked + 0];
    this.highlighted = false;
}
// This becomes the click() method.
function _ToggleButton_click()
{
    // Toggle the state of the button, change the image, and call the
    // onclick method, if it was specified for this ToggleButton.
    this.checked = !this.checked;
    this.image.src = ToggleButton.imagenames[this.checked+this.highlighted*2];
    if (this.onclick) this.onclick(this.checked);
}
// Initialize static class properties that describe the checkbox images. These
// are just defaults. Programs can override them by assigning new values.
// But they should only be overridden *before* any ToggleButtons are created.
ToggleButton.imagenames = new Array(4);            // Create an array.
ToggleButton.imagenames[0] = "images/button0.gif"; // The unchecked box
ToggleButton.imagenames[1] = "images/button1.gif"; // The box with a check mark
ToggleButton.imagenames[2] = "images/button2.gif"; // Unchecked but highlighted
ToggleButton.imagenames[3] = "images/button3.gif"; // Checked and highlighted
ToggleButton.width = ToggleButton.height = 25;     // Size of all images
</SCRIPT>
<!-- Here"s how we might use the ToggleButton class. -->
Optional extras:<br>
<script language="JavaScript1.1">
// Create ToggleButton objects and output the HTML that implements them.
// One button has no click handler, one has a function, and one has a string.
var tb1 = new ToggleButton(document, true, "56K Modem");
var tb2 = new ToggleButton(document, false, "Laser Printer",
                           function(clicked) {alert("printer: " + clicked);});
var tb3 = new ToggleButton(document, false, "Tape Backup Unit",
                     "alert("Tape backup: " + state)");
</script>
<!-- Here"s how we can use the ToggleButton objects from event handlers. -->
<form>
<input type="button" value="Report Button States"
       onclick="alert(tb1.checked + "\n" + tb2.checked + "\n" + tb3.checked)">
<input type="button" value="Reset Buttons"
       onclick="if (tb1.checked) tb1.click();
                if (tb2.checked) tb2.click();
                if (tb3.checked) tb3.click();">
</form>
</html>



Using the onSubmit Event to Cancel a Form Submission (Internet Explorer)

  
<HTML>
<HEAD>
<TITLE>On Close</TITLE>
<SCRIPT> 
function checkForm(e) { 
   if (!(window.confirm("Do you want to submit the form?"))) 
     e.returnValue = false; 
 } 
</SCRIPT>
</HEAD>
<BODY>
<FORM name="theForm" action="0801.html" 
   onSubmit = "return checkForm(event)">
<INPUT type=submit>
</FORM>
</BODY>
</HTML>