Become Zend Certified

Prepare for the ZCE exam using our quizzes (web or iPad/iPhone). More info...

When you're ready get 7.5% off your exam voucher using voucher CJQNOV23 at the Zend Store

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)
        <title>Different ways to access form values</title>
        <script type="text/javascript" src="/js/prototype.js"></script>
            <form method="post" id="sample-form">
                    <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()" />
        <script type="text/javascript">
            $('button1').observe('click', function(e) {
                var form = Event.findElement(e, 'form');
                var values = form.serialize(true);
            $('button2').observe('click', function(e) {
                var form = Event.findElement(e, 'form');
                var input = form.down('input[name=country]');
            $('button3').observe('click', function(e) {
                var form = Event.findElement(e, 'form');
                var input = form.down('input[name=country]');

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