PhpRiot
Download Article
Download this article or the entire “Eight Weeks of Prototype” series with all listings and files.




More information
Related Books
JavaScript: The Good Parts

JavaScript: The Good Parts

Most programming languages contain good and bad parts, but JavaScript has more than its share...

jQuery: Novice to Ninja

jQuery: Novice to Ninja

jQuery: Novice to Ninja is a compilation of best-practice jQuery solutions to meet the most...
PhpRiot Newsletter
Your Email Address:

More information

Eight Weeks of Prototype: Week 7, Other Prototype Functionality

Accessing Form Values

There are several ways to retrieve the value of a form element using Prototype. You can either retrieve the form element you want to read then access its value, or use Prototype to retrieve all values in a form then read the value that you require. 

Listing 5 shows three different ways to retrieve a form value. The first way serializes the form, allowing you to access the form using the element name. The second way retrieves the DOM element for the form element and calls the getValue() method. Finally, we use the $F(), which is an alias of the getValue() method.

Listing 5 Different ways to access form values (listing-5.html)
<html>
    <head>
        <title>Different ways to access form values</title>
        <script type="text/javascript" src="/js/prototype.js"></script>
    </head>
    <body>
        <div>
            <form method="post" id="sample-form">
                <div>
                    <input type="text" name="country" value="Australia" />
 
                    <input type="button" id="button1" value="Display with form.serialize()" />
                    <input type="button" id="button2" value="Display with Element.getValue()" />
                    <input type="button" id="button3" value="Display with $F()" />
                </div>
            </form>
        </div>
 
        <script type="text/javascript">
            $('button1').observe('click', function(e) {
                var form = Event.findElement(e, 'form');
 
                var values = form.serialize(true);
 
                alert(values.country);
            });
 
            $('button2').observe('click', function(e) {
                var form = Event.findElement(e, 'form');
 
                var input = form.down('input[name=country]');
 
                alert(input.getValue());
            });
 
            $('button3').observe('click', function(e) {
                var form = Event.findElement(e, 'form');
 
                var input = form.down('input[name=country]');
 
                alert($F(input));
            });
        </script>
    </body>
</html>

When you call the serialize() method on a form element, you need to pass true as the first argument for an object to be returned. If you don't, a serialized URL string will be returned instead (so in the case of this form, country=Australia would be returned).

In This Article