Coder Social home page Coder Social logo

maxatwork / form2js Goto Github PK

View Code? Open in Web Editor NEW
638.0 638.0 137.0 610 KB

Javascript library for collecting form data

Home Page: http://maxatwork.github.com/form2js/

License: MIT License

HTML 38.33% JavaScript 61.67%
form forms html javascript jquery jquery-plugin

form2js's People

Contributors

alejandroiglesias avatar danielalexiuc avatar danlo avatar emilgpa avatar fedott avatar francob411 avatar johnwlockwood avatar kaiju avatar leonidaz avatar lookfirst avatar maxatwork avatar mcasimir avatar petski 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

form2js's Issues

js2Form?

This little library is great. It is exactly what I'm looking for.

That said, I'd love the opposite direction as well.

I'd love to be able to take a chunk of json and have it apply to all of the input/textarea's on a page.

The usecase for this is handling of the 'cancel' button. I'd love to just reset everything to its prior values.

Thanks,

jon

Radio button true and false value bug

When a group of radios uses "true" or "false" for their values, form2js converts these to boolean true and false. However, if you add a 3rd radio to the group to indicate "none selected" or "no answer" or "any" and set its value to "", form2js will convert the checked radio with a value of "" to boolean false. However, if you don't use "true" and "false" as the values, the "" value works as expected.

This is because of the radio case in getFieldValue, which falls-through to the checkbox case. The offending line from the checkbox case is:

if(!fieldNode.checked && fieldNode.value === "true") return false;

This is correct for checkboxes, but for something like:

any
on
off

It is broken. I should not get back boolean false if the "any" radio is checked. I should get back "". To fix this, i just copied the statements from the checkbox case in getFieldValue, excluding the offending line, to the radio case.

Point is, this feels like a bug or maybe just unexpected behavior. IMHO, getFieldValue should not treat a radio just like a checkbox.

js2form don't feed any value

hi

i do a ajax call

i get this data

{  
   "lodgerId":1,
   "firstName":"Marc",
   "lastName":"Collin",
   "birthdate":"1979-03-02",
   "lodgerStatusId":0,
   "entryDate":"2015-07-22",
   "releaseDate":null,
   "phone":{  
      "phoneId":2,
      "phone":"(438) 392-3955",
      "phoneType":null,
      "extension":0
   },
   "identityCardList":[  
      {  
         "identityCardId":1,
         "identityCardType":{  
            "identityCardTypeId":1,
            "identityCardType":"Certificat de naissance",
            "dateFormat":null
         },
         "identyCardValue":"sdfasd",
         "expiration":null,
         "lodgerOwn":false
      }
   ],
   "oldAddress":{  
      "addressId":1,
      "name":"Père",
      "address":"906 boulé",
      "phone":{  
         "phoneId":1,
         "phone":"4506777244",
         "phoneType":null,
         "extension":0
      }
   },
   "vehicle":{  
      "vehicleId":1,
      "modelId":0,
      "color":"#e1e1e1",
      "licencePlate":"h8x2n4",
      "year":2005
   },
   "inactive":false
}

after i do

js2form($("#contactInformationForm"),data '.', null, false);

my web

<form id="contactInformationForm">
  <input type="hidden" class="form-control" name="lodgerId" id="lodgerId">
  <input type="text" class="form-control" id="lodgerFirstName" name="firstName">
  <input type="text" class="form-control" id="lodgerLastName" name="lastName">
  <input type="hidden" id="oldAddressAddressId" name="oldAddress.addressId">
  <input type="text" class="form-control" id="oldAddressName" name="oldAddress.name">
  <input type="text" class="form-control" id="oldAddressAddress" name="oldAddress.address" >
  <input type="hidden" name="identityCardList[0].identityCardId">
  <input type="text" class="form-control" id="idCardValue1" name="identityCardList[0].identyCardValue">
....
</form>

When i debug, i don't pass by any of the condition of this code in js2form.js

if (typeof formFieldsByName[fieldName] != 'undefined')
{
    setValue(formFieldsByName[fieldName], fieldValue);
}
else if (typeof formFieldsByName[fieldName.replace(_arrayItemRegexp, '[]')] != 'undefined')
{
    setValue(formFieldsByName[fieldName.replace(_arrayItemRegexp, '[]')], fieldValue);
}
else if (typeof formFieldsByName[fieldName.replace(_arrayItemRegexp, "")] != 'undefined') {
    setValue(formFieldsByName[fieldName.replace(_arrayItemRegexp, "")], fieldValue);
}

[enhancement] Add missing bower.json.

Hey, maintainer(s) of maxatwork/form2js!

We at VersionEye are working hard to keep up the quality of the bower's registry.

We just finished our initial analysis of the quality of the Bower.io registry:

7530 - registered packages, 224 of them doesnt exists anymore;

We analysed 7306 existing packages and 1070 of them don't have bower.json on the master branch ( that's where a Bower client pulls a data ).

Sadly, your library maxatwork/form2js is one of them.

Can you spare 15 minutes to help us to make Bower better?

Just add a new file bower.json and change attributes.

{
  "name": "maxatwork/form2js",
  "version": "1.0.0",
  "main": "path/to/main.css",
  "description": "please add it",
  "license": "Eclipse",
  "ignore": [
    ".jshintrc",
    "**/*.txt"
  ],
  "dependencies": {
    "<dependency_name>": "<semantic_version>",
    "<dependency_name>": "<Local_folder>",
    "<dependency_name>": "<package>"
  },
  "devDependencies": {
    "<test-framework-name>": "<version>"
  }
}

Read more about bower.json on the official spefication and nodejs semver library has great examples of proper versioning.

NB! Please validate your bower.json with jsonlint before commiting your updates.

Thank you!

Timo,
twitter: @versioneye
email: [email protected]
VersionEye - no more legacy software!

How to collect Date of birth as single value

Hi ,

I have 3 select tag for Data of Birth property in form but i want to collect them as a single value not 3 different value

As of now
"dd":"2",
"mm":"1",
"yyyy":"1993",

instead
dob:2/1/1993,

Ashish

js2form modifies SELECT element with disabled first option when property in JSON doesn't exist

When you run js2form on a SELECT element with a disabled first option, e.g.

<SELECT name="gender">
<option value="" disabled="disabled" selected="selected">Please select a gender</option>
<option value="M">Male</option>
<option value="F">Female</option>
</SELECT>

js2form would shift the SELECT element to select the first non-disabled option (in this example, Male), even if you don't pass in the "gender" property in the JSON.

The expected behavior is if the property doesn't exist in the JS object, then the SELECT element is not modified, regardless of whether the currently selected option is disabled or not.

The current workaround is to not use the "disabled" attribute on the first option and then use jQuery to add the "disabled" attribute to it again after js2form is called.

js2form nodecallback not used

i would really like this functionality as it came in very useful when extracting data from the forms i'm using.

i know that the work around is to transform my data into something that will fit into the form before submitting it to the js2form function, but i rather have the same shape of code for submitting data as extracting data. :)

Issue when using js2form

I have my form names in ruby-style syntax like a[b][c], but when using js2form the normalizeName process turns the object I pass into the a.b.c style names. This means that the input names to don't match the names the js2form function is creating for the object, so nothing gets filled in. Is this the intended behavior or am I missing something?

Problems in Ruby-style when key is one-char length

This does not work for me (using current master):

<label>person.ruby[field2][foo]<input type="text" name="person.ruby[field2][f]" value="baz" /></label>

Note that I use "f" instead of "foo". I get "Uncaught TypeError: Object # has no method 'push'"

Add typing to form fields

Hello,

I'd like to contribute to form2js by implementing a way to specify field types on form inputs. This would avoid generating an object like { balance: "-1.50", active: "true" } where it should be { balance: -1.50, active: true }. I've searched the issues and pull requests, but found something similar only for the boolean type.

I'm working on a web framework project which would benefit a lot from form2js. I wrote something similar to it, but it's only capable of converting simple form stuff.

Up to this point, the ideias I came up with are the following:

  • Use the type attribute, like <input type="number">, instead of type="text". This is HTML5-like, and has the advantage of displaying a numerical keyboard on mobile devices, while degrading gracefully to type="text" on non-compatible browsers (as far as I know). However, it would break compatibility with type="hidden" and also seem strange on select elements, like <select type="number"> (Eclipse displays a warning when validating XHTML).
  • Add some string to the class attribute, like class="type-number" or "type-boolean". It's XHTML compatible and minimally intrusive.

This might eliminate the need for specifying value="on" or value="true" on boolean checkboxes, allowing the string "true" to be used where it actually means a string value.

Any ideas or comments?

Thank you!
André

Ruby Style Arrays not Working

Ruby style arrays are not working for level 1 type arrays as follows:

testitem[test_property]

But it works for:

test.item[testproperty]

I guess the error is in

line 103

  •           if (namePart.length > 1)
    
  •           if (namePart.length > 0)
    

and

line 120

  •                   arrIdx = namePart[k].match(/([a-z_]+)?[([a-z_][a-z0-9]+?)]/i);
    
  •                   arrIdx = namePart[k].match(/([a-z_]+)?[([a-z_][a-z0-9_]+?)]/i);
    

N-Number of depth

Unable to parse this name: tables[1][features][0][title]

Please help this is a great plugin.

array for select box is not working

I have a table of form values, each row has different input types (based on column) like text and select box.

the text boxes are returned as array but the select box returns the last rows' value all the time.

Please let me know if there is a workaround ??

js2form node walking not working

Hi Max,

I've got a structure that looks like the html below. The issue is that the form isn't getting populated correctly. The phone field shows up fine, but none of the address fields show up. Stepping through the code, it appears as though js2form.getFields() doesn't walk the tree correctly. I see it find the 'addressInfo' id, but nothing within the table. Any ideas?

<table>
<tbody>
<tr>
    <th>Phone</th>
    <td><input type="text" id="phone" name="phone" /></td>
</tr>
<tr>
    <th>Address</th>
    <td>
        <table id="addressInfo" class="condensed-table">
            <tr>
                <th>Street 1</th>
                <td><input type="text" id="address.street1" name="address.street1" /></td>
            </tr>
            <tr>
                <th>Street 2</th>
                <td><input type="text" id="address.street2" name="address.street2" /></td>
            </tr>
            <tr>
                <th>City</th>
                <td><input type="text" id="address.city" name="address.city" /></td>
            </tr>
            <tr>
                <th>State</th>
                <td><input type="text" id="address.state" name="address.state" /></td>
            </tr>
            <tr>
                <th>Zip</th>
                <td><input type="text" id="address.zip" name="address.zip" /></td>
            </tr>
            <tr>
                <th>Country</th>
                <td><input type="text" id="address.country" name="address.country" /></td>
            </tr>
        </table>
    </td>
</tr>
</tbody>
</table>

unknown error: rootNode is null

screenshot 2015-03-13 20 20 49

Please see console output in the attached image. I save a Backbone object once with form2js and it works fine. But if I save a new object with the same view, I get this rootNode is null error. I can't find anything on Google for this error. Please help!

JSON Output format

I have following JSON format which comes dynamically:
{
"JSON": [
{
"key": "a",
"val": "aaa",
"sub": [
{
"key": "b",
"val": "bbb"
}
]
}
]
}
And I want to convert it in following output:

{
"JSON": [
{
"a": "aaa",
"sub": [
{
"b": "bbb"
}
]
}
]
}

Instead of key word I want actual Key-Value and instead of value word I want actual value.
So where to modify form2js.
My HTML is:

:

get the input value inside innerhtml

It won't get the values of input fields inside the innerhtml. i wonder if you can make it possible.. but it's already jQuery but just curious

Asp.Net MVC checkboxes special case

When an Asp.net MVC 3 view helper spits out a checkbox it puts a checkbox and a hidden text field in the html. This is to ensure that a value is passed back in a post even when the checkbox is not checked. The model binder on the server needs all the properties to have a value to ensure the proper model is bound, and thus the proper controller action method is invoked.

<input type="checkbox" value="true" name="IsFavorite" id="IsFavorite" />
<input type="hidden" value="false" name="IsFavorite"/>

So now the name/value pairs that are generated contain two values for the check box when it is checked, true and false. And false is the second value. So later in processNameValues the last value in wins.

A possible solution is to filter out duplicate values for check boxes. here is the relevant jQuery code I came up with. This generates my name/value list that I then pass into a modified version of your processNameValues function that takes in a json object to update instead of creating a new one. See issue #34.

function updateJson(form, json) {
    var arr = $(form).find(":input, :radio")
        .filter(function () {
            return this.name && !this.disabled &&
                (this.checked || /select|textarea/i.test(this.nodeName) ||
                    /text|hidden|password|search/i.test(this.type));
        })
        .map(function (i, elem) {
            var val = jQuery(this).val();
            return val == null ?
                null : { name: elem.name, value: val }
        }).get();
     $(form).find("input:checkbox")
        .filter(function () {
            return this.name;
        })
        .each(function(index, elem) {
            arr = $.grep(arr, function(item, index){
                return elem.name != item.name;
            });
            arr.push({ name: elem.name, value: (elem.checked ? "true" : "false") });
        });
    return processNameValues(json, arr, true, false);
}

form2js half working in the example

If you run /example/form2js.example.html, you will notice than the first simple input: FirstName, LastName and Gender are not present in the generated Json. But all the rest of the complex form is ok.

Any explanation?

Support for fieldset `name` attrribute

Apparently HTML5 provides this new fieldset name attribute where it is possible to inherit input values to its fieldset parent like:

<input name='event'>
<fieldset name='ticket'>
    <input name='price'>
    <input name='name'>
    <input name='description'>
</fieldset>

and in theory this would return:

where _ is some unknown separator

?event=test&ticket_price=75.00&ticket_name=test&ticket_description=description

I'm not sure if this is completely correct since it seems no browser implements this yet, but it is definitely a convenient way to format data . ;)

Update existing JSON object instead of new one

Thanks for the great script!

I am working on an asynchronous user interface application. I have a json object along with read-only and edit templates on the client. When the user invokes edit I can show the edit form instantly. I am now working on showing the new read-only view after the user hits save (with the new edited values) immediately. I found your code as a good solution for building that new JSON object to pass into the template engine.

I've made a local copy change to make the main methods take in a json object instead of creating a new one and it works. Do you think it is a fit in your project?

from this:

function form2js(rootNode, delimiter, skipEmpty, nodeCallback, useIdIfEmptyName){
}
function processNameValues(nameValues, skipEmpty, delimiter)
{
    var result = {},
    ...
    return result;
}

to this:

function form2js(rootNode, json, delimiter, skipEmpty, nodeCallback, useIdIfEmptyName)
{
    //... only change is to pass in new 'json' value to processNameValues ...
}
function processNameValues(json, nameValues, skipEmpty, delimiter)
{
    //... only change is to set values on 'json' parameter instead of 'result' variable
    return json;
}

you could still have an 'overload' for the current use case that just calls into the new method interface. That would keep the script backwards compatible and add only a couple lines of code to the file.

function form2js(rootNode, delimiter, skipEmpty, nodeCallback, useIdIfEmptyName)
{
    return form2js(rootNode, {}, delimiter, skipEmpty, nodeCallback, useIdIfEmptyName);
}
function processNameValues(nameValues, skipEmpty, delimiter)
{
    return processNameValues({}, nameValues, skipEmpty, delimiter);
}

Incorrect handling of ruby-style fields

Unfortunately the lack of comments in processNameValues makes it hard to work out if I'm just mistaken about how this works, but I was experiencing a bug using CakePHP trying to parse ruby-style field names. A checkbox list such as this: data[Topic][topic_id] was causing an error when I tried to parse it. Turns out the problem was the code:

arrIdx = namePart[k].match(/([a-z_]+)?\[([a-z_][a-z0-9]+?)\]/i);

The regexp doesn't allow an underscore in the rest of the name, which doesn't seem right to me. Seems like it should be:

arrIdx = namePart[k].match(/([a-z_]+)?\[([a-z_][a-z0-9_]+?)\]/i);

It seems to work perfectly after adding the extra underscore.

checkboxes should return JSON true/false

in the case of false (unchecked) it doesn't need to return anything as if(variable) will have the same behavior with null as with false. the 'false' case works. the 'true' case doesn't work.

will return

"exemption": {
    "enabled": "true"
},

where as it should return

"exemption": {
    "enabled": true
},

js2form: bind list of values to multiselect

js2form: list of values doesn't bind to multiselect.
Example:
I need to map object:

var x = {
    levels : ["DEBUG, ""INFO"]
};
js2form(form, x);

to the form with the control:

<select id="levels" name="levels" multiple="multiple"/>

It seems to me that js2form required select name "levels[]", but it's not correct fully.
The fix could look like addition another last "if" branch to the js2form function, I suppose:

      else if (typeof formFieldsByName[fieldName.replace(_arrayItemRegexp, '')] != 'undefined')
      {
        setValue(formFieldsByName[fieldName.replace(_arrayItemRegexp, '')], fieldValue);
      }

Ability to exclude a node in nodeCallback

Is there any way for me to force the exclusion of a node in my nodeCallback?

I have an attribute I'm setting on inputs when they change, and I can check for this in the nodeCallback, but I can't find anything to return that doesn't end up just adding unchanged elements to the object.

function cleanupFormValues(node) {  
  if (node.getAttribute && node.getAttribute('data-changed') === 'true') {
    if (node.type && node.type === 'checkbox') {
      return { name: node.id, value: node.checked ? true : false };
    } else {
      return false;
    }
  } else {
    return { name: '', value: null };
  }
}

Allow getting subset of a form

in your process code you start with :

...
    function getFormValues(rootNode, nodeCallback)
    {
        var result = [];
        var currentNode = rootNode.firstChild;
...

causing that you can not process a subset of a form like I would like to have to validate a part of the form with a query like this :

var jsonData = $('[name="food[]"]', myForm).toObject({mode : 'combine', skipEmpty : false});
...

feature: emptyToNull

I added this for form2js just above the skipEmpty line... basically, I want any empty value to be treated as null instead of empty string. This also works great with skipEmpty because then I don't have to send back empty values if I don't want to.

            if (emptyToNull && (value === '')) { value = null; }

object2array not producing correct array names 100% of the time

below is taken from the example html code in the dev branch, and my own.
i don't see a difference in my JSON or the example JSON... mine is valid and comes from couchDB.

the example JSON produces the array names properly.
18 Object { name="bar.Addresses[1].Zip", value="98765"}
19 Object { name="bar.Addresses[1].City", value="LA"}
20 Object { name="bar.Addresses[1].Street", value="Under the bridge"}

my JSON produces names that are not correct.
25 Object { name="taxes", value="2"}
26 Object { name="taxes", value="235235"}
27 Object { name="taxes", value=6}

{
"foo":{
"radio":"3",
"name":{
"first":"Foo-First",
"last":"Foo-Last"
},
"selectArray":[ "green", "yellow" ],
"checkboxArray":[ "steak", "chicken" ]
},
"bar":{
"name":{
"first":"Bar-First",
"last":"Bar-Last"
},
"Emails":[
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]"
],
"Addresses":[
{"Zip":"12345","City":"NY","Street":"13, Boardwalk"},
{"Zip":"98765","City":"LA","Street":"Under the bridge"}
]
}
}

from example JSON js2form.html

fieldValues
0 Object { name="foo.radio", value="3"}
1 Object { name="foo.name.first", value="Foo-First"}
2 Object { name="foo.name.last", value="Foo-Last"}
3 Object { name="foo.selectArray[0]", value="green"}
4 Object { name="foo.selectArray[1]", value="yellow"}
5 Object { name="foo.checkboxArray[0]", value="steak"}
6 Object { name="foo.checkboxArray[1]", value="chicken"}
7 Object { name="bar.name.first", value="Bar-First"}
8 Object { name="bar.name.last", value="Bar-Last"}
9 Object { name="bar.Emails[0]", value="[email protected]"}
10 Object { name="bar.Emails[1]", value="[email protected]"}
11 Object { name="bar.Emails[2]", value="[email protected]"}
12 Object { name="bar.Emails[3]", value="[email protected]"}
13 Object { name="bar.Emails[4]", value="[email protected]"}
14 Object { name="bar.Emails[5]", value="[email protected]"}
15 Object { name="bar.Addresses[0].Zip", value="12345"}
16 Object { name="bar.Addresses[0].City", value="NY"}
17 Object { name="bar.Addresses[0].Street", value="13, Boardwalk"}
18 Object { name="bar.Addresses[1].Zip", value="98765"}
19 Object { name="bar.Addresses[1].City", value="LA"}

20 Object { name="bar.Addresses[1].Street", value="Under the bridge"}

{
"_id": "HB - test",
"_rev": "1-a8cb317e9e4faf750d675843cb91c58e",
"ids": {
"chain": "hero burger",
"chain_min": "HB",
"store": "test store",
"store_min": "test",
"store_num": -1
},
"address": {
"country": "Canada",
"street": [
"adfaf",
"asdfasdf",
"asdf"
],
"city": "Toronto",
"state_prov": "Ontario",
"zip_postal": "M5N L7z",
"phones": [
"23452435",
"23452345",
"23452345"
],
"emails": [
"a@a",
"b@b",
"c@c"
]
},
"contact": "tony",
"operation_hours": [
{
"days": "asdfasfd",
"hours": "asfdasdf"
},
{
"days": "wrtt",
"hours": "rw"
}
],
"taxes": [
{
"taxId": "0",
"number": "23452345",
"percent": 4
},
{
"taxId": "1",
"number": "24352345",
"percent": 5
},
{
"taxId": "2",
"number": "235235",
"percent": 6
}
],
"exemption": {
"amount": "5.99",
"enabled": true
},
"website": "www.heroburger.com"
}

from my JSON

fieldValues
0 Object { name="_id", value="HB - test"}
1 Object { name="_rev", value="1-a8cb317e9e4faf750d675843cb91c58e"}
2 Object { name="ids.chain", value="hero burger"}
3 Object { name="ids.chain_min", value="HB"}
4 Object { name="ids.store", value="test store"}
5 Object { name="ids.store_min", value="test"}
6 Object { name="ids.store_num", value=-1}
7 Object { name="address.country", value="Canada"}
8 Object { name="address.street", value="adfaf\nasdfasdf\nasdf"}
9 Object { name="address.city", value="Toronto"}
0 Object { name="address.state_prov", value="Ontario"}
11 Object { name="address.zip_postal", value="M5N L7z"}
12 Object { name="address.phones", value="23452435\n23452345\n23452345"}
13 Object { name="address.emails", value="a@a\nb@b\nc@c"}
14 Object { name="contact", value="tony"}
15 Object { name="operation_hours", value="asdfasfd"}
16 Object { name="operation_hours", value="asfdasdf"}
17 Object { name="operation_hours", value="wrtt"}
18 Object { name="operation_hours", value="rw"}
19 Object { name="taxes", value="0"}
20 Object { name="taxes", value="23452345"}
21 Object { name="taxes", value=4}
22 Object { name="taxes", value="1"}
23 Object { name="taxes", value="24352345"}
24 Object { name="taxes", value=5}
25 Object { name="taxes", value="2"}
26 Object { name="taxes", value="235235"}
27 Object { name="taxes", value=6}
28 Object { name="exemption.amount", value="5.99"}
29 Object { name="website", value="www.heroburger.com"}

input with empty name returns `: 'value'`

Hi, when having an input without name perhaps the custom behaviour could be ignoring that node?

since it will generate a json like this:

{
      "" : "orphan node",
     "title" : "testing",
    ...
}

A way to create an empty list when no checkboxes are selected.

Given the following unselected inputs:

<dl>
    <dt>Favorite food</dt>
    <dd><label><input type="checkbox" name="person.favFood[]" value="steak"> Steak</label></dd>
    <dd><label><input type="checkbox" name="person.favFood[]" value="pizza"> Pizza</label></dd>
    <dd><label><input type="checkbox" name="person.favFood[]" value="chicken"> Chicken</label></dd>
</dl>

How could form2js build the following JSON for me?

{ person: { favFood: [] } }

One solution would be to cast a set of square brackets to an empty list. Then you could initialize any list you want to be empty by adding a hidden input as follows:

<dl>
    <dt>Favorite food</dt>
       <input type="hidden" name="person.favFood" value="[]" />
    <dd><label><input type="checkbox" name="person.favFood[]" value="steak"> Steak</label></dd>
    <dd><label><input type="checkbox" name="person.favFood[]" value="pizza"> Pizza</label></dd>
    <dd><label><input type="checkbox" name="person.favFood[]" value="chicken"> Chicken</label></dd>
</dl>

Any other ideas?

multiselect with name ending with []

form2js is excellent, searched for this solution for hours and I'm so glad that I didn't have to attempt to write a solution.

I have a multi select marked up as follows

<select name="categories[]" id="categories" multiple="multiple" class="multiple">
    <option value="News" label="News" selected="selected">News</option>
    <option value="Events" label="Events">Events</option>

    <option value="New Products" label="New Products" selected="selected">New Products</option>
</select>

if we have selected News and Events then formTo produces the following object from this...
{
...
"categories" : [ [ "News", "Events" ] ]
...
}

Whereas I required
{
...
"categories" : [ "News", "Events" ]
...
}

I solved the issue for my own needs by changing line 92 in form2object.js
from
name = nameValues[i].name;
to
name = nameValues[i].name.replace('[]','');

This doesn't seem to have any negative effects

I'm using Zend Form to create the form which adds the square brackets to the name if the element is expecting an array

NodeList undefined error in ie7, (solution included)

line 50 throws an error in ie7

solution is to change line 50 in form2object.js from

if (rootNode.constructor == Array || rootNode.constructor == NodeList )

to

 if (rootNode.constructor == Array || ( typeof NodeList != "undefined" && rootNode.constructor == NodeList ) )

Thanks

error when traversing back a nested level namespace

this will fail if you traverse back a level in the array:

 <form id="tests">
     <input name="something[something][title]" value="test"/>
     <textarea name="something[description]">Test</textarea>
 </form>

$('#tests').toObject();

Result:

Uncaught TypeError: Object # has no method 'push'

and to reorder so not traversing back results in an unexpected object:

<form id="tests">
    <textarea name="something[description]">Test</textarea>
    <input name="something[something][title]" value="test"/>
</form>

$('#tests').toObject();

Result:

something:
    0: "Test"
    something:
        title: "test"

Expected result for both cases:

something:
    description: "Test"
    something:
        title: "test"

Thank You

Hello Maxim,

Please excuse my abuse of the GitHub issues feature. I didn't see another way to contact you, but I just wanted to thank you for creating this package. I've found it very useful. Thanks!

Regards,
Craig

Repopulate form from JSON?

form2js has been a breakthrough in my coding - thank you!

Now that I can suck JSON out of my form, do you have a magical way to take the JSON object and repopulate the form fields with its data?

Before I spend an evening writing custom code, I thought I'd ask.

Is there a way to get disabled fields

Hi there. I've been doing some debugging, and I'm guessing that disabled fields are not serialized?

If that's the case, is there a way to turn that on? Like is there a way to get the disabled fields to be serialized?

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.