Web | This Site

Learn Prototype
Prototype Resources
Selected Reading
© 2011 TutorialsPoint.COM

| Home |  | References |  | Discussion Forums |  | About TP

# Prototype Form serialize() Method

This method is used to serialize form data to a string suitable for Ajax requests (default behavior) or, if optional getHash evaluates to true, an object hash where keys are form control names and values are data.

Depending of whether or not the optional parameter getHash evaluates to true, the result is either an object of the form {name: "johnny", color: "blue"} or a string of the form "name=johnny&color=blue", suitable for parameters in an Ajax request.

## Syntax:

    formElement.serialize([getHash = false]);

## Return Value :

- It returns an String object.

Here are two hints on how it works. For a detail look at the example below.

    $('example').serialize()
    // 'username=sulien&age=22&hobbies=coding&hobbies=hiking'
    $('example').serialize(true)
    // {username: 'sulien', age: '22', hobbies: ['coding', 'hiking']}

## Example:

    <html>
    <head>
    <title>Prototype examples</title>
       <script type="text/javascript"
       src="/javascript/prototype.js">
       </script>
    <script>

    function showResult()
    {
       var form = $('example');

       var element = form.serialize();
       alert("form.serialize() : " + element.inspect());
    }

    </script>
    </head>

    <body>

      <p>Click the button to see the result.</p>
      <br />

      <form id="example" action="#" onsubmit="return false">
      <fieldset><legend>User info</legend>
      <div><label for="username">Username:</label>
      <input name="username" id="username" value="Sulien" type="text">
      </div>
      <div><label for="age">Age:</label>
      <input name="age" id="age" value="23" size="3" type="text">
      </div>
      <div><label for="hobbies">Your hobbies are:</label>
      <select name="hobbies" id="hobbies" multiple="multiple">
        <option>coding</option>
        <option>swimming</option>
        <option>hiking</option>
        <option>drawing</option>
      </select></div>
      </fieldset>
      </form>

      <br />
      <input type="button" value="Result" onclick="showResult();"/>

    </body>
    </html>

To understand it in better way you can Try it yourself.

Advertisement

Online Image Processing

Indian Baby Names