Git Product home page Git Product logo

jquery-serialize-object's Introduction

jQuery Serialize Object

As seen on StackOverflow: Convert forms to JSON LIKE A BOSS.

Adds the method serializeObject to jQuery, to perform complex form serialization into JavaScript objects.

The current implementation relies in jQuery.serializeArray() to grab the form attributes and then create the object using the input name attributes.

This means it will serialize the inputs that are supported by .serializeArray(), that use the standard W3C rules for successful controls to determine which inputs should be included; in particular:

  • The input cannot be disabled and must contain a name attribute.
  • No submit button value is serialized since the form is not submitted using a button.
  • Data from <input type="file"> inputs are not serialized.

Installation

option 1: NPM

$ npm install form-serializer

option 2: Bower

$ bower install jquery-serialize-object

option 3: Manual

Copy the dist/jquery.serialize-object.min.js to your project.

You can include the plugin in the HEAD element or at the bottom of your BODY tag. Wherever you choose to add it, it must be included after your jQuery.

<head>
  <script src="jquery.min.js"></script>
  <script src="jquery.serialize-object.min.js"></script>
</head>

2.0

Version 2.0 takes jquery-serialize-object into maturity. It is now backed by a full test suite so you can be confident that it will work in your web app.

Moving ahead, on top of core serialization, .serializeObject will support correct serializaton for boolean and number values, resulting valid types for both cases.

Look forward to these >= 2.5.0

Update: >= 2.4.0 now serializes <input type="checkbox"> as a boolean. See the test for specific behavior.

API

Given a basic HTML form

<form id="contact">
  <input name="user[email]" value="[email protected]">
  <input name="user[pets][]" type="checkbox" value="cat" checked>
  <input name="user[pets][]" type="checkbox" value="dog" checked>
  <input name="user[pets][]" type="checkbox" value="bird">
  <input type="submit">
</form>

.serializeObject — serializes the selected form into a JavaScript object

$('form#contact').serializeObject();
//=> {user: {email: "[email protected]", pets: ["cat", "dog"]}}

.serializeJSON — serializes the selected form into JSON

$('form#contact').serializeJSON();
//=> '{"user":{"email":"[email protected]","pets":["cat","dog"]}}'

FormSerializer.patterns — modify the patterns used to match field names

Many of you have requested to allow - in field names or use . to nest keys. You can now configure these to your heart's content.

Hyphen example

$.extend(FormSerializer.patterns, {
  validate: /^[a-z][a-z0-9_-]*(?:\[(?:\d*|[a-z0-9_-]+)\])*$/i,
  key:      /[a-z0-9_-]+|(?=\[\])/gi,
  named:    /^[a-z0-9_-]+$/i
});

Dot-notation example

$.extend(FormSerializer.patterns, {
  validate: /^[a-z][a-z0-9_]*(?:\.[a-z0-9_]+)*(?:\[\])?$/i
});

Validating and Key parsing

  • validate — only valid input names will be serialized; invalid names will be skipped

  • key — this pattern parses all "keys" from the input name; You will want to use /g as a modifier with this regexp.

Key styles

  • push — push a value to an array

    <input name="foo[]" value="a">
    <input name="foo[]" value="b">
    $("form").serializeObject();
    //=> {foo: [a, b]}
  • fixed — add a value to an array at a specified index

    <input name="foo[2]" value="a">
    <input name="foo[4]" value="b">
    $("form").serializeObject();
    //=> {foo: [, , "a", , "b"]}
  • named — adds a value to the specified key

    <input name="foo[bar]" value="a">
    <input name="foo[bof]" value="b">
    <input name="hello" value="world">
    $("form").serializeObject();
    //=> {foo: {bar: "a", bof: "b"}, hello: "world"}

Tests

If you have node.js installed, as a convenience, you can run

$ npm test

If you do not have node installed, simply

$ open ./test/test.html

CoffeeScript

CoffeeScript has been dropped for >= 2.0.0. If members of the community would like to support this, please feel free to add a CoffeeScript version.

If you'd like to use the the 1.0.0 version, it is still available here.

Contributing

See : CONTRIBUTING

jquery-serialize-object's People

Contributors

alanning avatar malteriechmann avatar maxkoryukov avatar nickforddev avatar pnikolov avatar thebeardedllama avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

jquery-serialize-object's Issues

Support ordered named keys

Hashes/objects in JavaScript are not guaranteed to maintain their order when iterating them in JavaScript. Sometimes order is important.

How about an alternative serialization format where a form like

<input type="text" name="obj[b-key]" value="b-val">
<input type="text" name="obj[a-key]" value="a-val">

Will be serialized to:

{
    obj: [
        ["b-key","b-val"],
        ["a-key","a-val"]
    ]
}

instead of

{
   obj: {
       "b-key":"b-val", 
       "a-key": "a-val"
   }
}

Which might lose its order?

Support composer

Can you add support for composer? Version in NPM is outdated (

Problem with select boxes

Hi,

I made a fiddle of the issue here - http://jsfiddle.net/QqT2w/1/

Basically there's a hiccup involving encoding forms like this:

select name="p[89][panel1]"

The information is encoded correctly, but there's a problem with a lot of additional undefined data also being attached.

Thanks for the great solution by the way. I hope this can improve it..

Support: Want to exclude some values

Hi,

I have a control which is composite control of many inputs i.e. text, select.
The control is a repating control so it has a copy of controls meant to be clone I want to exclude the last group value from result.

Also, I am not getting value for this tables[0][title]

Thanks
-Shak

Table with Rows and Columns

I need to convert the form which as rows and cols dynamically added into form to objects.
Form fields are declared has below

      <input name="cols[]" value="col1"/>
      <input name="cols[]" value="col2"/>

To each col added rows will have

    <input name="row[row1][col1]" value="one"/>
    <input name="row[row1][col2]" value="two"/>
    <input name="row[row2][col1]" value="three"/>
    <input name="row[row2][col2]" value="four"/>

I could not generate the porper object like
cols:["col1", "col2"]
row :{row1:["one","two"],"row2:["three","four"]}

Please let me know what is wrong here

I modified the serialize object as below

    $.fn.serializeObject = function serializeObject() {
        var data = {},pushes = {};
          patterns = {
            validate: /^[a-z][a-z0-9_-]*(?:\[(?:\d*|[a-z0-9_]+)\])*$/i,
            key: /[a-z0-9_-]+|(?=\[\])/gi,
            push: /^$/,
            fixed: /^\d+$/,
            named: /^[a-z0-9_-]+$/i
          };

        if (this.length > 1) {
          return new Error("jquery-serialize-object can only serialize one form at a time");
        }
        var pairs = this.find('input,select,textarea').serializeArray();
        if (!$.isArray(pairs)) {
            throw new Error("Fields expects an Array");
          }
          for (var i=0, len=pairs.length; i<len; i++) {
            var pair = pairs[i],value;
            //console.log( pair.name + " : " + patterns.validate.test(pair.name)  );
            if (patterns.validate.test(pair.name)) { 

              var keys = pair.name.match(patterns.key), k;

              // nest, nest, ..., nest
              while ((k = keys.pop()) !== undefined) {
                // foo[]
                if (patterns.push.test(k)) {

                  var key = pair.name.replace(/\[\]$/, '');
                    if (pushes[key] === undefined) {
                        pushes[key] = 0;
                    }                     
                  var idx = pushes[key]++;
                  var obj = []
                  obj[idx] = pair.value;          
                  value = obj;
                }

                // foo[n]
                else if (patterns.fixed.test(k)) {

                      var obj = []
                      obj[k] = pair.value;      
                      value = obj;
                }

                // foo; foo[bar]
                else if (patterns.named.test(k)) {

                      var obj = {};
                      obj[k] = pair.value;
                      value = obj ;
                }
              }
              data = $.extend(true, data, value);       
            }
          }     

        return data;
   };

Conflicts with RequireJS

Attempting to include your plugin in an environment that uses RequireJS results in the following error from RequireJS:

Error: Mismatched anonymous define() module: function ($, exports) { factory(root, exports, $); }

RequireJS uses define and apparently defines define.amd as well which make your plugin think it is "AMD" (which I don't know what is in this context)

Incorrect JSON generation for nested attribute.

Hey,

I was using your jQuery plugin and have encountered this weird behaviour.

<!DOCTYPE html>
<html>

<head>
    <script type="text/javascript" src="jquery.js"></script>
    <script type="text/javascript" src="jquery.serialize-object.js"></script>
</head>

<body>
    <form id="new_form">
        User Name:
        <input type="text" name="agent_signup[user_name]">
        <br>
        User Email:
        <input type="text" name="agent_signup[user_user_emails_attributes[0][email]]">
        <br>
        Agent Role
        <input type="checkbox" name="agent_signup[role_ids][]" value="1">Account Administrator
        <input type="checkbox" name="agent_signup[role_ids][]" value="2">Administrator
        <input type="checkbox" name="agent_signup[role_ids][]" value="4">Agent
        <input type="checkbox" name="agent_signup[role_ids][]" value="3">Supervisor
        <button>Submit</button>
    </form>
</body>

</html>

To serialize the form, I ran

$("#new_form").serializeObject()

The returned object was

"{"agent_signup":{"user_name":"tushar","role_ids":["1","2"]}}"

whereas the expected object is

"{"agent_signup":{"user_name":"tushar","user_user_emails_attributes":{"0":{"email":"[email protected]"}},"role_ids":["1","2"]}}"

Doesn't support non-object "keys"

There's no support for anything I'm trying to do here because it seems that there's only support for object dot-notation syntax.

  <input type="hidden" name="customer_properties[$email]" value="[email protected]">
  <input type="hidden" name="properties[Total Price]" value="24.99">
  <input type="hidden" name="properties[Items Purchased][]" value="Cheerios">
  <input type="hidden" name="properties[Items Purchased][]" value="Milk">
  <input type="hidden" name="properties[Items Purchased][]" value="Cereal Bowls">

This should be totally valid

Allow dashes in element names

Currently the function excludes any elements in the form that contain a dash in the name attribute, however using dashes are completely valid according the the W3C spec.

To include elements with dashed names in the returned object, I just updated the patterns.validate, patterns.key, and patterns.named regular expressions to include a dash in their character sets resulting in the following:

patterns = {
    validate: /^[a-zA-Z][a-zA-Z0-9_-]*(?:\[(?:\d*|[a-zA-Z0-9_]+)\])*$/,
    key: /[a-zA-Z0-9_-]+|(?=\[\])/g,
    push: /^$/,
    fixed: /^\d+$/,
    named: /^[a-zA-Z0-9_-]+$/
};

uglify-js version in package.json is incompatible with NPM

I'm using NPM version 2.1.18

npm ERR! Darwin 14.0.0
npm ERR! argv "node" "/usr/local/bin/npm" "install"
npm ERR! node v0.10.31
npm ERR! npm  v2.1.18
npm ERR! code ETARGET

npm ERR! notarget No compatible version found: uglify-js@'>=2.4.32 <3.0.0'
npm ERR! notarget Valid install targets:
npm ERR! notarget ["0.0.1","0.0.2","0.0.3","0.0.4","0.0.5","1.0.1","1.0.2","1.0.3","1.0.4","1.0.5","1.0.6","1.0.7","1.1.0","1.1.1","1.2.0","1.2.1","1.2.2","1.2.3","1.2.4","1.2.5","1.2.6","1.3.0","1.3.1","1.3.2","1.3.3","1.3.4","2.2.0","2.2.1","2.2.2","2.2.3","2.2.4","2.2.5","2.3.0","2.3.1","2.3.2","2.3.3","2.3.4","2.3.5","2.3.6","1.3.5","2.4.0","2.4.1","2.4.2","2.4.3","2.4.4","2.4.5","2.4.6","2.4.7","2.4.8","2.4.9","2.4.10","2.4.11","2.4.12","2.4.13","2.4.14","2.4.15","2.4.16"]
npm ERR! notarget 
npm ERR! notarget This is most likely not a problem with npm itself.
npm ERR! notarget In most cases you or one of your dependencies are requesting
npm ERR! notarget a package version that doesn't exist.

npm ERR! Please include the following file with any support request:

Seems that the latest version is 2.4.16

Problem with nested JSON objects.

I am trying to create a nested JSON object, but I can't figure out how to name the fields correctly. The JSON format I want to create is this:

{
   "character": [
     {
       "male": text,
       "female": text,
       "result": text,
        "itinerary": [
            {
                "activity": text,
                "lat": number,
                "long”: number
            },
            {
                "activity": text,
                "lat": number,
                "long”: number
            },
            {
                "activity": text,
                "lat": number,
                "long”: number
            }
        ]
     }
 ]
}

I can’t figure out how to name the fields for the itinerary.activity, itinerary.lat, and itinerary.long fields to make the nested array. I’ve tried character[][itinerary][activity], character[][itinerary][][activity], and character[]itinerary[][activity]. The first one creates a new { itinerary } block for each set of fields, the second one creates an increasing number of “null” values in each consecutive object, and the third one doesn’t include the itinerary data at all. Is there another way I’m not seeing?

Is there a way to pass an array of Key Value pairs?

I have a form that includes a number of fields.

Everything works perfectly except for an array of text values.

I am trying to get my JSON to look like this:

{"Id":"123","MiscValue":"LoremIpsum","YearlyValues":[{"Year":2014, "Value":"100.00"},{"Year":2013, "Value":"115.00"},{"Year":2012, "Value":"90.00"}], ... }

Currently it looks like:

... "YearlyValues":[{"Value":"100.00"},{"Value":"115.00"},{"Value":"90.00"}]...

using the (simplified) HTML of:

<label>2014</label>
<input name="YearlyValues[][Value]" class="form-control" id="YearlyValues[][Value]" type="text" value="100.00" />

<label>2013</label>
<input name="YearlyValues[][Value]" class="form-control" id="YearlyValues[][Value]" type="text" value="115.00" />

<label>2012</label>
<input name="YearlyValues[][Value]" class="form-control" id="YearlyValues[][Value]" type="text" value="90.00" />

I have tried adding the year in there but I continue to get the wrong json. Any ideas?

Missing empty values

How to reproduce
Use the following demo - http://jsfiddle.net/9xfdvLbL/

Conditions
Typing some copy in the input text and by selecting one or more categories, you get:

{"filtering":{"title":"john doe","categories":["1","3"]}}

Problem
When submitting the form without entering any values in the form fields. You get:

{"filtering":{"title":""}}

Expectation
When submitting the form with no values in the fields to get:

{"filtering":{"title":"","categories":[]}}

Chrome crashes when using serializeJSON

Not sure if this is a real bug, but it annoys me since it crashes my Chrome every time I do it.
JSFiddle: http://jsfiddle.net/1skp3rg7/3/

I have 3 buttons, each one triggers the following corresponded function.
I have an array named aa[20141225][date].
In the JSFiddle example, serializeObject and serializeArray work just fine, but serializeJSON crashes my browser (using chrome). When you test it please be aware that clicking serializeJSON will crash your browser, I need to refresh my page when it crashes. :D

serializeJSON()
serializeObject()
serializeArray()

I suspect it treats my nested array 20141225 that it is actually an index of an array and therefore it is allocating that many elements in an array until it ran out allocated memories and eventually crashed.
How would I make 20141225 parsed as a string key?

jQuery 2.x

Not sure if there's a reason for this, but the bower.json requires jQuery 1.x

Some of the other bower libraries in my app require jQuery 2.x, so this leads to some confusing conflicts come bower install time. If I choose to use jQuery 2.x the jquery-serialize-object library works just fine (tested with jQuery 2.1.3 and a simple $('form').serializeObject()).

Any reason for the ^ here? Can we just change that to a >=?

Cheers

Support for keys with hyphens

Thanks so much for creating this code. I was especially interested in getting hyphenated input names to work.

In using the code you provided in your Readme, I found that an input name such as foo[bar-baz] still does not work, but this can be fixed by updating the relevant group in the patterns.validate regex to include a dash, as follows:

$.extend(FormSerializer.patterns, {
  validate: /^[a-z][a-z0-9_-]*(?:\[(?:\d*|[a-z0-9_-]+)\])*$/i,
  key:      /[a-z0-9_-]+|(?=\[\])/gi,
  named:    /^[a-z0-9_-]+$/i
});

Support for disabled fields

Would be great if we can tell to jquery-serialize-object to return disabled fields too. Something like:

$('form').serializeObject({getDisabled: true});

Support inputs without form

The jQuery serialize functions can be called on either a form element a collection of individual inputs. When I try using serializeObject on a collection of inputs, it says "jquery-serialize-object can only serialize one form at a time".

IE8 support

Hey Macek,

I'm using this plugin for a project and it works fine in all browser beside IE8. Does the plugin support IE8 or is it not supported? I can't find any information about browser support.

In IE8 after calling $("#form").serializeJSON(); simply nothing happens. It just stops. No error, nothing.

Cheers,
Konrad

Ability to omit form fields.

Hey! Great tool. I can't believe jquery does not have this feature. Must be stuck in Web 2.0 ;)

I think this issue is like #46 but I'm not sure. Essentially I am using stripe.js to convert credit card data to a hash for my application to use. I would like to pass my API all the form details except for the fields related to credit card data.

It would be awesome if this tool could omit form fields that were marked with a particular class or data attribute.

If you point me in the right direction I could take a stab at it as well.

Thanks!

serializeJSON not exposed to global jQuery?

Not sure if that is the right terminology, but I'm trying to incorporate this plugin into my JS project and I cannot seem to be able to access serializeJSON from the global jQuery scope. Example:

$('#edit_quote').serializeJSON()

Outputs

Uncaught TypeError: Object [object Object] has no method 'serializeJSON'

I have ensured that jQuery has been loaded first. It won't work in a jsFiddle either: http://jsfiddle.net/wmt62/

Any help would be appreciated!

IE8 - n.patterns.validate is null or not an object

In IE8 when calling serializeObject, I get an error of n.patterns.validate is null or not an object. I'm not passing any extra parameters in, just calling it:

var formData = $(this).serializeObject();

Support of the jQuery-ui datepicker's altField

It is not a news that dates and JSON are total nightmare. The jQuery-ui datepicker has an altField element that is together with the altFormat is designed for this:

This allows one date format to be shown to the user for selection purposes, while a different format is actually sent behind the scenes.

Unfortunately neither form.serialise() nor form.serializeArray() use this element. As a results dates got passed as a clear text and if you are not happen to live in USA you are in trouble.

I think, it is not difficult to enhance your function to use the altField, as it already re-tests the values from DOM for checkboxes in the encode() function. I recommend it also tests for altField. All it needs to do is check if altField is defined

Test all keys before deciding on 'fixed' array

I had a form with a mix of numeric and string keys. This serializer decided my form should be serialized using a fixed array, causing me to lose chunks of the form that used named keys.

Hey macek, coding problem

Hey, trying to get this form to work but it's not giving me the result set I want. here is my code

Does not work with dynamically added inputs.

I tried using this script on a form in which I add a number of hidden input fields via jQuery when an event is added via FullCalendar. However when I serialize the form none of the hidden inputs are converted.
This worked with a different script I was using but it did not convert inputs into arrays like name='dates[]

partial form serialization support

So, if I don't want to edit the field names, but, I want to use your plugin to build up a specific JSON model to post to my API controller, I think it would be great if partial form serialization was supported..

So, I could do this ...

```javascript
function createMyFormModel() {
  var base, model, obj1, obj2;

  base = this;
  obj1 = $("tr.itemsOnOrder").serializeObject();
  obj2 = $("tr.newItemsToAdd").serializeObject();
  return model = {
      ItemsOnOrder: obj1,
      EligibleItems: obj2
  };
};
```javascript

Install with composer

Sorry but it seems I cant find the project in packagist.org.
Has it not been uploaded there or am I missing something?

Symmetrical setter function "setJSON" would be nice

Your plugin is exactly what I was looking for, but sometimes it's necessary to also set the form values from object, which would be reverse of this toJSON e.g. named form.setJSON(object).

Ideally toJSON output should be usable in setJSON directly, that is: form.setJSON(form.toJSON()) would work as expected, keeping values intact (though it should trigger changed events of course).

I know you haven't needed it, but I might implement it based on your toJSON solution if I can't find anything that does it. Will post my setJSON in public domain, and notify this issue when I find it.

Standalone JSON String Parse

I love the concept, but I'm working with a framework that provides me a json string already. I'd love to just pass this in and parse it. Is this possible?

crash maybe due to incorrect array length

I got this form, with the following json structure:

[{"name":"slots[1395086400]","value":"0"},{"name":"slots[1395086400]","value":"1"},{"name":"slots[1395090000]","value":"0"},{"name":"slots[1395090000]","value":"1"},{"name":"slots[1395172800]","value":"0"},{"name":"slots[1395172800]","value":"1"},{"name":"slots[1395176400]","value":"0"},{"name":"slots[1395176400]","value":"1"},{"name":"slots[1395259200]","value":"0"},{"name":"slots[1395259200]","value":"1"},{"name":"slots[1395262800]","value":"0"},{"name":"slots[1395262800]","value":"1"},{"name":"slots[1395345600]","value":"0"},{"name":"slots[1395345600]","value":"1"},{"name":"slots[1395349200]","value":"0"},{"name":"slots[1395349200]","value":"1"},{"name":"slots[1395432000]","value":"0"},{"name":"slots[1395432000]","value":"1"},{"name":"slots[1395435600]","value":"0"},{"name":"slots[1395435600]","value":"1"},{"name":"slots[1395518400]","value":"0"},{"name":"slots[1395518400]","value":"1"},{"name":"slots[1395522000]","value":"0"},{"name":"slots[1395522000]","value":"1"}]"

when calling serializeObject() on this form , this is what I get logged :

Object {slots: Array[1395522001]}
  slots: Array[1395522001]
    1395086400: "1"
    1395090000: "1"
    1395172800: "1"
    1395176400: "1"
    1395259200: "1"
    1395262800: "1"
    1395345600: "1"
    1395349200: "1"
    1395432000: "1"
    1395435600: "1"
    1395518400: "1"
    1395522000: "1"
    length: 1395522001 // really?!
  __proto__: Array[0]
  __proto__: Object

Trying to access the slots property causes immediate crash with Chrome, not in Firefox, but they both have the incorrect length value.

Edit: the form consists of multiple checkboxes, and each has its checkbox with negative value so it can be sent even if it's unchecked. See: http://stackoverflow.com/questions/1809494/post-the-checkboxes-that-are-unchecked

serialize to result start with array []

<input name="foo[]" value="10">
<input name="foo[]" value="20">

serialize into

{foo: [10, 20]}

How can I serialize a form into below without the key 'foo'

[10, 20]

Support "dot" notation for object property names

This is a rad plugin! I personally think it would be cool if it also supported dot notation, e.g:

<input name="dream.as.vividly.as.you.can" value="g">

would parse the same as:

<input name="dream[as][vividly][as][you][can]" value="g">

Support for Browserify

This doesn't seem to work with Browserify. I see CommonJS support in the source, so apologies if the problem lies in my own code.

As I understand, setup should be pretty simple:

var $ = require('jquery');
require('form-serializer');

However I get a TypeError: undefined is not a function when I call $('form').serializeObject(), indicating the methods aren't attached to the object.

support serialization of elements whose names begin with an "_"

Currently form elements with names that begin with an underscore are ignored.

I already have a PR outstanding so I don't want to mess that up by including another commit but the fix for this is to change this line: https://github.com/macek/jquery-serialize-object/blob/master/jquery.serialize-object.js#L31

 validate: /^[a-z][a-z0-9_]*(?:\[(?:\d*|[a-z0-9_]+)\])*$/i,

... to this:

 validate: /^[_a-z][a-z0-9_]*(?:\[(?:\d*|[a-z0-9_]+)\])*$/i,

(Note the addition of the underscore in the first bracket group.)

support serialization of elements whose names include "-"

Currently form elements with names that begin with an underscore are ignored.

I already have a PR outstanding so I don't want to mess that up by including another commit but the fix for this is to change this line: https://github.com/macek/jquery-serialize-object/blob/master/jquery.serialize-object.js#L31

validate: /^[_a-z][a-z0-9_]*(?:\[(?:\d*|[a-z0-9_]+)\])*$/i,

... to this:

validate: /^[_a-z][a-z0-9_\-]*(?:\[(?:\d*|[a-z0-9_\-]+)\])*$/i,

Multiple select

I had a 'multiple' attribute in my select element and only the last selected value would get passed along.

Basically I edited one function and added another. To me it seems 'dirty'.

function getMultiple(pairs,multiName,current)
{
  var multipleValues = [];
  for (var i = current; i<pairs.length; i++)
  {
    if(pairs[i].name === multiName)
        multipleValues.push(pairs[i].value);
    else
        break;
  };
    var obj = makeObject(multiName, encode({name:multiName,value: multipleValues}));
    data = helper.extend(true, data, obj);
    return i;
}

function addPairs(pairs) {
  if (!helper.isArray(pairs)) {
    throw new Error("formSerializer.addPairs expects an Array");
  }
  for (var i=0, len=pairs.length; i<len; i++) 
  {
    if($('[name="'+pairs[i].name+'"]').attr('multiple') )
    {
        i = this.getMultiple(pairs,pairs[i].name,i);
    }
    else
        this.addPair(pairs[i]);
  }
  return this;
}

Also added the following to the public API:

this.getMultiple = getMultiple;

I have NOT tested anything beside that I get a object with named key and an 'array' as value IE:

Object{
name : array[x]
0 : 'value',
1 : 'value',
2 : 'value',
}
etc

I wonder if multiple select is going to be supported?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.