How to serialize a form into an object (with tree structure)?

前端 未结 2 842
南方客
南方客 2021-01-06 17:00

I have a form

2条回答
  •  渐次进展
    2021-01-06 17:51

    Something like the following should work:

    function serializeData() {
        //this is where we'll store our serialized data
        var serializedData = {};
    
        //iterate over input, select, and textarea elements
        jQuery("input, select, textarea").each(function(index) {
           var $element = jQuery(this);
           var name = $element.attr("name");
    
           //we only want to serialize the element if it has a 'name' attribute
           if(typeof name != "undefined") {
    
              //split on the . to get an array
              var parts = name.split(/\./);
    
              //start building the serialized data
              var currentPart = serializedData;
              for(var i = 0; i < parts.length; i++) {
    
                  //if this particular element doesn't already exist in our hash, create it
                  //and initialize it to an empty hash
                  if(typeof serializedData[parts[i]] == "undefined") {
                      currentPart[parts[i]] = {};
                  }
    
                  //if we're currently looking at the very last element in the array then
                  //it means that we need to set its value to the value of the corresponding
                  //input element. Otherwise, it means that there are still keys within the
                  //array and so we set `currentPart` to the new hash that we just created
                  if(i == parts.length - 1) {
    
                      //if the element is a checkbox or a radio, we need to see if it's checked
                      //instead of looking at its value
                      if($element.attr("type").toLowerCase() == "checkbox" || $element.attr("type").toLowerCase() == "radio") {
                          currentPart[parts[i]] = $element.is(":checked");
                      }
    
                      else {
                         currentPart[parts[i]] = $element.val();
                      }
                  }
    
                  else {            
                      currentPart = currentPart[parts[i]];
                  }                   
              }
           }
        });
    
        console.log(serializedData);
    }
    

    Check out the fiddle.

    All you need to do now is to bind serializeData to the submit event on the form.

提交回复
热议问题