jQuery serializeArray() key value pairs

前端 未结 10 1809
無奈伤痛
無奈伤痛 2020-11-28 06:25

I\'m having a bit of trouble serializing a form

10条回答
  •  抹茶落季
    2020-11-28 06:30

    The accepted answer works great if your form doesn't have checkboxes or radio buttons. Since groups of those all have the same name attribute, you need to create an array value inside the object. So for html like:

    
    
    
    

    You'll get:

    {the-checkbox:['1', '2', '3']}
    

    This bit of code handles everything nicely.

    /*!
     * jQuery serializeObject - v0.2 - 1/20/2010
     * http://benalman.com/projects/jquery-misc-plugins/
     * 
     * Copyright (c) 2010 "Cowboy" Ben Alman
     * Dual licensed under the MIT and GPL licenses.
     * http://benalman.com/about/license/
     */
    
    // Whereas .serializeArray() serializes a form into an array, .serializeObject()
    // serializes a form into an (arguably more useful) object.
    
    (function($,undefined){
      '$:nomunge'; // Used by YUI compressor.
    
      $.fn.serializeObject = function(){
        var obj = {};
    
        $.each( this.serializeArray(), function(i,o){
          var n = o.name,
            v = o.value;
    
            obj[n] = obj[n] === undefined ? v
              : $.isArray( obj[n] ) ? obj[n].concat( v )
              : [ obj[n], v ];
        });
    
        return obj;
      };
    
    })(jQuery);
    

    Usage

    $(form).serializeObject();
    

提交回复
热议问题