serialize form in javascript

 1  function serialize(form) {
 2         var parts = new Array();
 3         var field = null;
 4 
 5         for (var i = 0, len = form.elements.length; i < len; i++) {
 6             field = form.elements[i];
 7 
 8             switch (field.type) {
 9                 case "select-one":
10                 case "select-multiple":
11                     for (var j = 0, optLen = field.options.length; j < optLen; j++) {
12                         var option = field.options[j];
13                         if (option.selected) {
14                             var optValue = "";
15                             if (option.hasAttribute) {
16                                 optValue = (option.hasAttribute("value") ? option.value : option.text);
17                             } else {
18                                 optValue = (option.attributes["value"].specified ? option.value : option.text);
19                             }
20                             parts.push(encodeURIComponent(field.name) + "=" + encodeURIComponent(optValue));
21                         }
22                     }
23                     break;
24                 case undefined:
25                 case "file":
26                 case "submit":
27                 case "reset":
28                 case "button":
29                     break;
30                 case "radio":
31                 case "checkbox":
32                     if (!field.checked) {
33                         break;
34                     }
35                 default:
36                     parts.push(encodeURIComponent(field.name) + "=" + encodeURIComponent(optValue));
37             }
38         }
39         return parts.join("&");
40     }

 

posted on 2013-05-16 20:50  雷音  阅读(176)  评论(0编辑  收藏  举报

导航