Web Development Tutorials




  
  

Buttons

Buttons defined by the <input type="button"> tag have been used to capture events and run scripts. Buttons can also serve as data input methods by associating values with them. The general format for the <input type="button"> tag is shown below.


<input type="button"
  id="id"
  value="string" />

Figure 9-28. General format for <input type="button"> tag.

The value attribute serves two purposes. It provides the label that appears on the button as well as the value associated with the button. An id is not required unless the button is referred to in a script.

Using Buttons for Data Entry

When one of the following number buttons is clicked, its value is appended to the value in the accompanying text box. When the "C" button is clicked, the value in the text box is cleared. When the "<<" button is clicked, the final character in the field is erased. Use of buttons in this fashion is the basis for JavaScript calculators.


Figure 9-29. Using buttons for data entry.


<script type="text/javascript">
window.onload = init;

function init()
{
   var x = document.getElementsByName("btnNumber");
   var btnErase = document.getElementById("btnErase");
   var btnClear = document.getElementById("btnClear");

   btnClear.onclick = clearNumber;
   btnErase.onclick = erase;

   for (i = 0; i>x.length; i++)
   {
      x[i].onclick = append;
   }
}

function append()
{
   document.getElementById("number").value += this.value;
}

function erase()
{
   var length = document.getElementById("number").value.length;
   document.getElementById("number").value = 
   document.getElementById("number").value.substring(0, length-1);
}

function clearNumber()
{
   document.getElementById("number").value = "";
}
</script>

<input type="button" value="0" name="btnNumber">
<input type="button" value="1" name="btnNumber">
<input type="button" value="2" name="btnNumber">
<input type="button" value="3" name="btnNumber">
<input type="button" value="4" name="btnNumber">
<input type="button" value="5" name="btnNumber">
<input type="button" value="6" name="btnNumber">
<input type="button" value="7" name="btnNumber">
<input type="button" value="8" name="btnNumber">
<input type="button" value="9" name="btnNumber">
<input type="button" value="." name="btnNumber">
<input type="text" id="number" style="width:100px; text-align:right">
<input type="button" id="btnErase" value="<<">
<input type="button" id="btnClear" value="C">

Listing 9-19. Code to use buttons for data entry.

When a number button is clicked, its onclick event handler calls the Append() function to concatenate the passed value to the display area. Clicking the "C" button clears the display area. The EraseCharacter() function removes the last character in the display field by copying all but the last character back into the field. This replacement substring is extracted from the displayed value with the string method substring(0,Length-1): the string of characters beginning with the first character (0) and continuing for Length-1 characters.

The <button> Tag

The <button> tag provides greater versatility in producing buttons. As a container tag, it can enclose any text or HTML code to provide text and/or graphic displays on the face of the button. The general format for this tag is shown below.


<button id="id">		
  text and XHTML tags...
</button>

Figure 9-30. General format for <button> tag.

In the following example, three buttons are formatted with images and text. A click on a button opens a secondary window to display a Web page.


Figure 9-31. Using <button> tags as links.


<button style="width:200px; padding:1px; border:outset 3px"
  onclick='open("../../html/default.aspx", "", "")'>
  <img src="html_tutorial.png" style="width:150px">
  <b>HTML&CSS Tutorial</b>
</button>

<button style="width:200px; padding:1px; border:outset 3px"
  onclick='open("../default.aspx", "", "")'>
  <img src="javascript_tutorial.png" style="width:150px">
  <b>JavaScript Tutorial</b>
</button>

Listing 9-20. Code to use <button> tags as links.

Any text, HTML, and/or images can be coded between the opening and closing <button> tags. You may need to apply style settings to the button to get enclosed content positioned properly.

Buttons Events and Handlers

Either of the button types can trap for mouse events surrounding the button. These events and their handlers are summarized in the following table.

Event Handler Event
onclick The mouse is clicked and released with the cursor positioned over the button.
ondblclick The mouse is double-clicked with the cursor positioned over the button.
onmousedown The mouse is pressed down with the cursor positioned over the button.
onmouseout The mouse cursor is moved off the button.
onmouseover The mouse cursor is moved on top of the button.
onmouseup The mouse button is released with the cursor positioned over the button.

Figure 9-32. Event handlers associated with button events.

The onclick and ondblclick handlers are used to trap mouse clicks on buttons for the purpose of calling functions to carry out processing. The remaining handlers are most often used to style the button to provide visual clues to actions surrounding the button. In the following example, a <button> tag is styled on mouseover and mouseout events.



Figure 9-33. Styling a button through mouse events.


<button style="width:200px; padding:5px; border:outset 3px"
  onclick=    "open('../default.aspx', '', '')"
  onmouseover="document.getElementById('Text').innerHTML='Link to Tutorial';
               document.getElementById('Pic').src='./images/javascript_tutorial.png';
               this.style.border='inset 3px'"
  onmouseout= "document.getElementById('Text').innerHTML='JavaScript Tutorial';
               document.getElementById('Pic').src='./images/javascript_tutorial2.png';
               this.style.border='outset 3px'">
  <img id="Pic" src="./images/javascript_tutorial2.png" style="width:150px"/><br/>
  <span id="Text" style="font-weight:bold">JavaScript Tutorial</span>
</button>

Listing 9-21. Code to style a button through mouse events.

Inline scripts apply style settings on mouseover and mouseout events. In both cases, the text label of the button is changed by assigning a different text string to the innerText property of the <span> tag surrounding the text; the picture is changed through the src property of the <img> tag; and the border style of the button is changed between outset and inset styles. Note that the <img> and <span> tags require ids for reference from within the scripts; border style changes use self-references to the button itself (this).

A Simple Calculator

Use of buttons to create a simple JavaScript calculator is demonstrated below.

JavaScript Calculator

Formula:

Figure 9-34. A simple JavaScript calculator.

The HTML code and button event handlers are shown below. The calculator is formatted inside a table to control its layout.


<table border="7">
<tr>
  <td colspan="4" style="font-family:comic sans ms; text-align:center; 
  color:white; background-color:gray; font-size:9pt">
    JavaScript Calculator
  </td>
</tr>
<tr>
  <td colspan="3"><input id="Answer" type="text" style="width:100px; text-align:right"></td>
  <td><input type="button" style="width:30px" value="=" onclick="EnterEqual()"></td>
</tr>
<tr>
  <td><input type="button" style="width:30px" value="1" onclick="EnterNumber(this.value)"></td>
  <td><input type="button" style="width:30px" value="2" onclick="EnterNumber(this.value)"></td>
  <td><input type="button" style="width:30px" value="3" onclick="EnterNumber(this.value)"></td>
  <td><input type="button" style="width:30px" value="+" onclick="EnterOperator(this.value)"></td>
</tr>
<tr>
  <td><input type="button" style="width:30px" value="4" onclick="EnterNumber(this.value)"></td>
  <td><input type="button" style="width:30px" value="5" onclick="EnterNumber(this.value)"></td>
  <td><input type="button" style="width:30px" value="6" onclick="EnterNumber(this.value)"></td>
  <td><input type="button" style="width:30px" value="-" onclick="EnterOperator(this.value)"></td>
</tr>
<tr>
  <td><input type="button" style="width:30px" value="7" onclick="EnterNumber(this.value)"></td>
  <td><input type="button" style="width:30px" value="8" onclick="EnterNumber(this.value)"></td>
  <td><input type="button" style="width:30px" value="9" onclick="EnterNumber(this.value)"></td>
  <td><input type="button" style="width:30px" value="*" onclick="EnterOperator(this.value)"></td>
</tr>
<tr>
  <td><input type="button" style="width:30px" value="C" onclick="EnterClear()"></td>
  <td><input type="button" style="width:30px" value="0" onclick="EnterNumber(this.value)"></td>
  <td><input type="button" style="width:30px" value="." onclick="EnterNumber(this.value)"></td>
  <td><input type="button" style="width:30px" value="/" onclick="EnterOperator(this.value)"></td>
</tr>
</table>
<input id="Formula" type="hidden"/>

Listing 9-22. Code to format and style the calculator.

Notice the final <input id="Formula" type="hidden"/> field. The type="hidden" attribute creates a standard textbox that is hidden from view. In the example above, this control is given the attribute type="text" in order to make it visible so you can see the formulas being created by the button clicks.

Four functions are called by the buttons. All of the number keys call function EnterNumber(), passing the number value of the button; the arithmetic operator keys call function EnterOperator(), passing the operator symbol; the "=" key calls function EnterEqual(); and the "C" key calls function EnterClear().


<script type="text/javascript">
var op = false;
var eq = false;

function EnterNumber(Number)
{
  if (op == false) {
    document.getElementById("Formula").value += Number;
    document.getElementById("Answer").value += Number; }
  else {
    document.getElementById("Answer").value = Number;
    op = false;
    if (eq == true) {
      document.getElementById("Formula").value = Number;
      eq = false; }
    else {
      document.getElementById("Formula").value += Number; 
    }
  }
}

function EnterOperator(Operator)
{
  if (document.getElementById("Formula").value != "") {
    document.getElementById("Answer").value = 
      eval(document.getElementById("Formula").value);
    document.getElementById("Formula").value = 
      eval(document.getElementById("Formula").value) + Operator;
    op = true;
    eq = false;
  }
}

function EnterEqual()
{
  if (document.getElementById("Formula").value != "") {
    document.getElementById("Answer").value = 
      eval(document.getElementById("Formula").value);
    document.getElementById("Formula").value = 
      eval(document.getElementById("Formula").value);
    op = true;
    eq = true;
  }
}

function EnterClear()
{
  document.getElementById("Answer").value = "";
  document.getElementById("Formula").value = "";
  op = false;
  eq = false;
}

</script>

Listing 9-23. Script for the calculator.

In general, a call to EnterNumber() concatenates the passed value to the end of the Answer textbox string and to the end of the Formula hidden textbox string. A call to EnterOperator() evaluates the Formula and displays the result in Answer. The function also replaces the Formula with the result and concatenates the operator in preparation for the next entered number. This pattern of function calls continues for additional numbers and operators entered. When the "=" button is clicked, function EnterEqual() is called to produce an Answer and a new Formula much like a call to EnterOperator(), except that no operator is concatenated to the Formula since this is the end of the series of calculations.

There is a need to keep track of whether an operator button or equal button was clicked in order to determine how to handle the next click on a number key. If an operator button was just clicked, then the next number entered replaces the result showing in the Answer box; if an operator button was not clicked, then the next number is concatenated to the number in the box. Likewise, replacement or concatenation takes place in the Formula box depending on whether the equal button was just clicked. This need to keep track of a previous operator or equal button click is handled by the global variables op and eq. These variables are set to true and false to indicate the current condition under which various replacements or concatenations are applied.

Other than this need to track button clicks, the script is fairly straight-forward. Build a Formula, evaluate the Formula and replace the Answer and Formula, then continue building the next Formula. These operations should be apparent from viewing the visible Formula textbox.



TOP | NEXT: Validating Forms