Chapter 27. Scripting Buttons

Probably the most common form control is the button. Even though you can submit a form by calling its submit() method (and thus without using a submit button), most forms have a button because of the relationship between a form and its controls.

Button controls can be created in one of two ways. You can use the <input/> element, like this:

<input type="submit" name="myButton" value="Button Text" />

Or you can use the <button/> element, like this:

<button type="submit" name="myButton2" value="Button Text"/>

Regardless of how you create a button, you can directly access its DOM object in one of two ways. First, you can get to the button through the form. The following code shows how to access the <input/> element named myButton (from the top of the page), assuming it's in a form named theForm:

var button = document.theForm.myButton;

Form control objects are automatically added as properties to the forms they reside in. So this code first gets the <form name="theForm" /> element object and then gets the myButton property. The second way to get to the button through the form is the ever-easy document.getElementById() method, but in the case of the myButton button, getElementById() will not work because it has no id attribute.

After you have access to the DOM object, you can manipulate it however you see fit. For example, the following code sets a click event handler (using the event utility) to modify the button every time it's clicked:

var count = 0;
var button = document.theForm.myButton;

eventUtility.addEvent(button, "click", function(event) {
var eSrc = eventUtility.getTarget(event);

    eSrc.value = "You clicked me " + ++count + " times.";
});

This code creates two variables called count and button. The former is used to count how many times the button is clicked, and the latter gets the <input/> element's DOM object. With a reference to that object, the code then sets an event handler to handle the click event. When the button is clicked, the button's value property is changed to reflect the number of times the button has been clicked. A button's value property gets or sets the text that is displayed within the button.

Note

Remember that ++ is an increment operator, and that when it appears before a variable, the value in the variable is incremented before the variable's value is returned.

There is a flaw in this event handler, however. Assuming that the myButton button is part of the theForm form, clicking the button causes the form to submit. Its type attribute is set to submit, so this isn't very surprising. This is easy enough to fix; simply call eventUtility.preventDefault() and the form will not submit. The default action of a submit button is to submit the form it resides in. So when you click a submit button, a series of events fire in the following order:

  1. mousedown

  2. mouseup

  3. click

  4. submit

The submit event does not fire until after the click event fires, and since submit is the default event of a submit button, calling preventDefault() will prevent the submit event from firing. The same can be said for buttons of type reset. The reset event fires after click, and calling preventDefault() in the handler for click suppresses the reset event.

For the most part these same concepts apply to buttons created with the <button/> element. According to the HTML specification, it doesn't really matter how you create a button; the <button/> element does allow you to add content to it, however, as shown in the following HTML code:

<button name="myButton3" type="submit">
    <p id="buttonContent">Button Text</p>
</button>

Here a <p/> element with an id of buttonContent contains the text "Button Text", and it is added as a child to <button/>. This content renders inside the <button/>, so the content dictates what the user sees as opposed to the value property of the <input/> element.

What makes <button/> elements so different, as far as scripting is concerned, is that the content within the button can also be the target of an event. So in order to replicate the functionality from the click event handler for the myButton button, a few changes must be made to the event handler function.

Assume the myButton3 button replaces the myButton button in the theForm form, and look at the following code:

var count = 0;
var button = document.theForm.myButton3;

eventUtility.addEvent(button, "click", function(event) {
    var content = document.getElementById("buttonContent");

    content.innerHTML = "You clicked me " + ++count + " times.";
    eventUtility.preventDefault(event);
});

The event handler in this code gets the <p/> element by using getElementById(), and then sets its innerHTML to reflect the number of times the button has been clicked. This is absolutely the easiest approach. Otherwise you would have to acquire the event target, check to see if the target is the <p/> element, and, if it's not, search for that element in the DOM tree. So if you plan on using the <button/> element, and you want to modify its contents, put an id attribute on the elements you want to modify.

Even though you can modify a button in this way, chances are pretty good that the only modification you'll make to a button is disabling it. If you visit discussion boards often you may have noticed something along the lines of a double post. A double post is caused when the user fills out the form, clicks the submit button, and then clicks it again before the browser loads the server's response from the first submission. It's a common problem wherever forms appear, and it can cause serious problems if the user double-posts a form to make a purchase.

You'll look at how to disable a button in the following Try It section.

TRY IT

In this lesson, you learn about the button control, and the differences between creating them with <input/> and <button/> elements.

Lesson Requirements

For this lesson, you need a text editor; any plain text editor will do. For Microsoft Windows users, Notepad is available by default on your system or you can download Microsoft's free Visual Web Developer Express (www.microsoft.com/express/web/) or Web Matrix (www.asp.net/webmatrix/). Mac OS X users can use TextMate, which comes as part of OS X, or download a trial for Coda (www.panic.com/coda/). Linux users can use the built-in VIM.

You also need a modern web browser. Choose any of the following:

  • Internet Explorer 8+

  • Google Chrome

  • Firefox 3.5+

  • Apple Safari 4+

  • Opera 10+

Create a subfolder called Lesson27 in the JS24Hour folder you created in Lesson 1. Store the files you create in this lesson in the Lesson27 folder.

Step-by-Step

  1. Type the following HTML:

    <html>
    <head>
        <title>Lesson 27: Example 01</title>
    </head>
    <body>
    <form name="theForm" action="" onsubmit="validateForm(event)">
        <input name="btnSubmit" type="submit" value="Submit" />
    </form>
    <script type="text/javascript" src="eventutility.js"></script>
    <script type="text/javascript">
    
    </script>
    </body>
    </html>

    Save this as lesson27_example01.htm. The page consists of one <form/> named theForm. It has an onsubmit event handler set to the validateForm() function. Inside the form is a submit button named btnSubmit.

  2. Now add the bold lines in the following code:

    <html>
    <head>
        <title>Lesson 27: Example 01</title>
    </head>
    <body>
    <form name="theForm" action="" onsubmit="validateForm(event)">
        <input name="btnSubmit" type="submit" value="Submit" />
    </form>
    <script type="text/javascript" src="eventutility.js"></script>
    <script type="text/javascript">
    function validateForm(event) {
        var button = document.theForm.btnSubmit;
    
        button.disabled = true;
    
        var notValidated = confirm("Do you want to simulate an invalid form?");
    }
    </script>
    </body>
    </html>

    This code adds the validateForm() function, and it accepts an event object as an argument. The first line of the function gets the submit button and stores it in the button variable. Then you disable the button by assigning true to the disabled property. The last line of this code simulates a validation error: It calls the confirm() method to ask if you want to simulate a validation error. If you click OK, notValidated is true. If Cancel, notValidated is false.

  3. Nothing happens when you click OK or Cancel in the confirm box at this point, so add the following bold code:

    <html>
    <head>
        <title>Lesson 27: Example 01</title>
    </head>
    <body>
    <form name="theForm" action="" onsubmit="validateForm(event)">
        <input name="btnSubmit" type="submit" value="Submit" />
    </form>
    <script type="text/javascript" src="eventutility.js"></script>
    <script type="text/javascript">
    function validateForm(event) {
        var button = document.theForm.btnSubmit;
    
        button.disabled = true;
    
        var notValidated = confirm("Do you want to simulate an invalid form?");
    
        if (notValidated) {
            alert("Invalid data was found in the form. Please fix and submit
    again");
            button.disabled = false;
            eventUtility.preventDefault(event);
        }
    }
    </script>
    </body>
    </html>

    This new code checks the value of notValidated. If it's true (meaning a simulated validation error took place), an alert box tells the user that something is invalid and to fix the error. After the alert box is dismissed, the button is re-enabled by having its disabled property set to false, and the call to eventUtility.preventDefault() prevents the form from being submitted.

    Of course, if the Cancel button is clicked, meaning that notValidated is false, then the form submits and reloads the page to simulate the validation of all fields.

In some of the future lessons, you build off this example and perform actual validation routines.

To get the sample code files, you can download Lesson 27 from the book's website at www.wrox.com.

Note

Please select Lesson 27 on the DVD to view the video that accompanies this lesson.

Step-by-Step
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.218.157.34