jQuery: The Write Less, Do More JavaScript Library

Ajax/serialize

From jQuery JavaScript Library

Jump to: navigation, search

« Back to Ajax

serialize( )

Serializes a set of input elements into a string of data. This will serialize all given elements.
As of jQuery 1.2 the serialize method correctly serializes forms. For older versions of jQuery, the Form Plugin's fieldSerialize method should be used.

Examples:
Serialize a form to a query string, that could be sent to a server in an Ajax request.

    function showValues() {
      var str = $("form").serialize();
      $("#results").text(str);
    }

    $(":checkbox, :radio").click(showValues);
    $("select").change(showValues);
    showValues();

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
                    "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <script src="../jquery-latest.js"></script>
  
  <script>
  $(document).ready(function(){
    
    function showValues() {
      var str = $("form").serialize();
      $("#results").text(str);
    }

    $(":checkbox, :radio").click(showValues);
    $("select").change(showValues);
    showValues();

  });
  </script>
  <style>
  body, select { font-size:12px; }
  form { margin:5px; }
  p { color:red; margin:5px; font-size:14px; }
  b { color:blue; }
  </style>
</head>
<body>
  <form>
    <select name="single">
      <option>Single</option>
      <option>Single2</option>
    </select>
    <select name="multiple" multiple="multiple">
      <option selected="selected">Multiple</option>
      <option>Multiple2</option>
      <option selected="selected">Multiple3</option>
    </select><br/>
    <input type="checkbox" name="check" value="check1"/> check1
    <input type="checkbox" name="check" value="check2" checked="checked"/> check2
    <input type="radio" name="radio" value="radio1" checked="checked"/> radio1
    <input type="radio" name="radio" value="radio2"/> radio2
  </form>
  <p><tt id="results"></tt></p>
</body>
</html>

NameType