Sunday 20 November 2011

jQuery Serialize

jQuery Serialize



[{name:"first",value:"Rick"},
{name:"last",value:"Astley"},
{name:"job",value:"Rock Star"}]
 
 
 
Note: Because some frameworks have limited ability to parse serialized arrays, we should exercise caution when passing an obj argument that contains objects or arrays nested within another array.
In jQuery 1.4 HTML5 input elements are serialized, as well.
We can display a query string representation of an object and a URI-decoded version of the same as follows:
var myObject = {
  a: {
    one: 1, 
    two: 2, 
    three: 3
  }, 
  b: [1,2,3]
};
var recursiveEncoded = $.param(myObject);
var recursiveDecoded = decodeURIComponent($.param(myObject));

alert(recursiveEncoded);
alert(recursiveDecoded);
The values of recursiveEncoded and recursiveDecoded are alerted as follows:
a%5Bone%5D=1&a%5Btwo%5D=2&a%5Bthree%5D=3&b%5B%5D=1&b%5B%5D=2&b%5B%5D=3
a[one]=1&a[two]=2&a[three]=3&b[]=1&b[]=2&b[]=3









Example : Serialize a key/value object.

<!DOCTYPE html>
<html>
<head>
<style>
div { color:red; }
</style>
<script src='http://code.jquery.com/jquery-latest.js'></script>
</head>
<body>
<div id="results"></div>
<script>
var params = { width:1680, height:1050 };
    var str = jQuery.param(params);
    $("#results").text(str);
</script>
</body>
</html>
 
 
 
 
 
 
 
 
 
=========================================================================
 
 
 
 
 
 
 
 
 
 
<!DOCTYPE html>
<html>
<head>
<style>
body, select { font-size:12px; }
  form { margin:5px; }
  p { color:red; margin:5px; font-size:14px; }
  b { color:blue; }
</style>
<script src='http://code.jquery.com/jquery-latest.js'></script>
</head>
<body>
<form>
    <select name="single">
      <option>Single</option>
      <option>Single2</option>
    </select>

<br />
    <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" id="ch1"/>

    <label for="ch1">check1</label>

    <input type="checkbox" name="check" value="check2" checked="checked" id="ch2"/>

    <label for="ch2">check2</label>
<br />
    <input type="radio" name="radio" value="radio1" checked="checked" id="r1"/>

    <label for="r1">radio1</label>
    <input type="radio" name="radio" value="radio2" id="r2"/>

    <label for="r2">radio2</label>
  </form>
  <p><tt id="results"></tt></p>
<script>
function showValues() {
      var str = $("form").serialize();
      $("#results").text(str);
    }
    $(":checkbox, :radio").click(showValues);
    $("select").change(showValues);
    showValues();
</script>
</body>
</html>
 

No comments:

Post a Comment