macek / jquery-serialize-object Goto Github PK
View Code? Open in Web Editor NEWConverts HTML form into JavaScript object
License: Other
Converts HTML form into JavaScript object
License: Other
When a fieldname startst with a number, it is not serialized, although it is in the output of serializeArray.
http://plnkr.co/edit/Qx8EZixStTeWiwZZUAB2?p=preview
Is that fixable? The fieldname is a token that is rendered and I don't have control over.
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;
};
Hey, trying to get this form to work but it's not giving me the result set I want. here is my code
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
<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]
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.)
The README.md looks great as far as what it is, the API, etc. However for a brand new jQuery user, there is no information or instructions on how to use it in their web page.
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..
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?
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".
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">
Sorry but it seems I cant find the project in packagist.org.
Has it not been uploaded there or am I missing something?
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
});
As title, can we parse complex path-name like w3c suggested? http://www.w3.org/TR/2014/WD-html-json-forms-20140529/
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?
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
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.
when submitting the console will write " " and "{ }"
Would be cool if this were available through their CDN.
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!
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,
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
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
this is one thing that has been missing from jQuery core.
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":[]}}
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
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
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
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[]
Hello, how I can make it work with HTML element's name contains "-" such as
<input name="name-of-this-element" value="xxx" />
Thank
Can you add support for composer? Version in NPM is outdated (
if you have a number of checkboxes, only the ones that are checked will be serialized (with "on")
Hi @macek ,
It is possible to add feature to include unchecked checkbox into the object or json result, something like
{
"some_unchecked_checkbox" : false
}
regards
Ikhsan
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_-]+$/
};
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.
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?
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?
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)
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();
form
select
option>add me to the serializeObject</option
/select
/form
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?
Would be great if we can tell to jquery-serialize-object to return disabled fields too. Something like:
$('form').serializeObject({getDisabled: true});
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?
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.
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"]}}"
The returned object contains only a single value for a <select multiple>
with multiple values selected.
The expected value would be an array with all selected values.
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
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!
Hi,
First of all Great plugin!
I am looking for a JSON object to form functionality like the one below:
https://github.com/maxatwork/form2js/blob/master/src/js2form.js
If you have any future plan on it.
Thanks
-Shak
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.