Giter VIP home page Giter VIP logo

form-data-json's Introduction

Hi @all ๐Ÿ‘‹

I am Roland Eigelsreiter aka BrainFooLong, i full-time web developer from austria. With focus on PHP and JS. I create and contribute to open source software as often as i can.

๐Ÿ‘ท Check out what I'm currently working on

  • frmlx/framelix - A rich featured, Full-Stack PHP framework with built-in backend and data management capabilities for internal/public data applications. (2 months ago)
  • brainfoolong/form-data-json - A zero dependency, cross browser library to easily get or set/manipulate form input values as/from a json object. (2 months ago)
  • brainfoolong/js-ascon - JavaScript / TypeScript Implementation of Ascon, a family of authenticated encryption (AEAD) and hashing algorithms designed to be lightweight. (3 months ago)
  • NullixAT/browstorjs - Persistent key/value data storage for your Browser and/or PWA, promisified, including file support and service worker support, all with IndexedDB. Perfectly suitable for your next (PWA) app. (4 months ago)
  • brainfoolong/gdscript-midi-parser - Godot GDScript 4+ Midi File Parser and Player (5 months ago)
  • brainfoolong/cryptojs-aes-php - CryptoJS AES encryption/decryption on client side with Javascript and on server side with PHP (6 months ago)
  • brainfoolong/php-ascon - PHP 8+ Implementation of Ascon, a family of authenticated encryption (AEAD) and hashing algorithms designed to be lightweight (6 months ago)

๐ŸŒฑ My latest projects

๐Ÿ”ญ Latest releases I've contributed to

  • brainfoolong/form-data-json (2.2.2, 2 months ago) - A zero dependency, cross browser library to easily get or set/manipulate form input values as/from a json object.
  • brainfoolong/cryptojs-aes-php (2.3.0, 7 months ago) - CryptoJS AES encryption/decryption on client side with Javascript and on server side with PHP
  • NullixAT/browstorjs (1.3.0, 1 year ago) - Persistent key/value data storage for your Browser and/or PWA, promisified, including file support and service worker support, all with IndexedDB. Perfectly suitable for your next (PWA) app.

๐Ÿ”จ My recent Pull Requests

๐Ÿ““ Gists I wrote

โญ Recent Stars

๐Ÿ‘ฏ Check out some of my recent followers

form-data-json's People

Contributors

brainfoolong 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

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

form-data-json's Issues

Automatic array processing while fromJson

Hi!
I`v got a form and get a data from DB for It. The data has the same structure:

{
  Company: [
    {
      id: 2,
      name: 'PanamaServ',
      Address: [
        {
          Country: [
            {
              id: 2,
              name: 'USA',
            },
          ],
          address: 'Porkold 11a',
          city: 'NewYork',
          company_id: 2,
          country_id: 2,
          id: 4,
          post_code: 34246,
          region:'ZP',
        },
      ],
      Email: [
        {
          company_id: 2,
          email: '[email protected]',
          id: 3,
        },
        {
          company_id: 2,
          email: '[email protected]',
          id: 2,
        },
      ],
    },
  ],
}

It is necessary to use array because the DB can returns multiple objects. So therefore I should use corresponding names for input fields of the form:

name="Company[0][Address][0][country_id]"
name="Company[0][Email][0][email]"

It is inconvenient to get first element always.

It would be great the fromJson method automatically get first element of an array. And returns callback to process the array in custom function and logging to the console to inform a user if the array has multiple elements.
I think it might looks like:

function process_array ( array ) {
    return array[2];
}

It Probably needs an option for this behavior.

Manipulating defaults for FormDataJsonOptions

Make defaults possible to edit by code.

Adding a static property defaults with key/value pair instead of pre-filled property values should do the trick. So the user can edit the defaults property to their needs.

radio element value 0

Hi

First of all thanks for plugin

I am not filling radio element if its value is 0. ()
if I convert to string or bigger then 0 it is ok.
ex : { opened : 0 } not running

Doesn't work when inputs are nested more than one child element deep

Is your feature request related to a problem? Please describe.
Hi, I know this is probably a rare problem and I can find a workaround if needed, but I was wondering if there is a way for the library to work with forms who's inputs aren't the direct children of the form element. For example, I have a situation where each form is a table row, with each input in a cell across like so:

<tr>
        <form id="example">
          <td>
              <input type='text' name='firstName' class="inputLine" placeholder="First Name"></input>
          </td>
          <td>
              <input type='text' name='lastName' class="inputLine" placeholder="Last Name"></input>
          </td>
          <td>
              <input type='email' name='email' class="inputLine" placeholder="Email"></input>
          </td>
        </form>
      </tr>

If I try use this form in the library, it does not pull the input values. I am assuming that this is because the library looks for inputs that are only the direct children of the form. Is there a way to make this work somehow? If not, will it work if I use divs instead of TD's?

Describe the solution you'd like
Maybe a parameter on the function to specify how many nested in the inputs are.

v2-dev: make `uncheckedValue` false by default

Is your feature request related to a problem? Please describe.

	<input type="checkbox" name="scales[]">
	<input type="checkbox" name="scales[]" value="77">

image

Describe the solution you'd like
If uncheckedValue is undefined by default then result of .toJson can not be passed .fromJson
eg. operation is not reversable

At this example we have two check boxes. Second have value 77. And when we setup { scales: ['77'] } nothing is selected, because first checkbox does not have 77 value.

So in this case we need to loop over all checkboxes with scales names to work properly.
Even doing so, we have corner case:

	<input type="checkbox" name="scales[]">
	<input type="checkbox" name="scales[]">
	<input type="checkbox" name="scales[]" value="77">

When second scales is checked result will be { scales: [ 'on' ] }. And we will not know which was checked: first or second??

So for consistent results and for reverse (result of .toJson can be passed back .fromJson (so backend can send data as is)): please make uncheckedValue false by default

Thank you

Proposal to Improve the Manipulation of Masked Field Values in Forms

It would be good to have a way to manipulate the value of the field, for example, fields that use masks (like currency) are bringing the complete string "USD$ 100.32".

Just as we have the filterInput function, there could be something that iterates between the fields and allows us to manipulate the field's return; it would give much more flexibility to the developer.

This way, I could take the field that has the mask and process the value to return it as a number "100.32".

Selection of checkboxes should based on values instead of order in DOM

Describe the bug
When filling the form with data using FormDataJson.fromJson .... for checkboxes the checkbox is only selected if the data provided is the exact order that checkboxes appear in the DOM

To Reproduce
In the following example https://jsfiddle.net/yusafme/vuj3kth5/3/ the checkboxes are checked as you would expect

<form>
  Email<input name="communication[preference][]" type="checkbox" value="email">
  SMS<input name="communication[preference][]" type="checkbox" value="sms">
  Letter<input name="communication[preference][]" type="checkbox" value="letter">
</form>
<script>
let form = document.querySelector("form")
FormDataJson.fromJson(form, {communication:{
	preference:["email", "sms"]
}});
</script>

However in this example https://jsfiddle.net/yusafme/vuj3kth5/4/ only the first checkbox is checked, but you would want both the email checkbox and letter checkbox to be checked

<form>
  Email<input name="communication[preference][]" type="checkbox" value="email">
  SMS<input name="communication[preference][]" type="checkbox" value="sms">
  Letter<input name="communication[preference][]" type="checkbox" value="letter">
</form>
<script>
let form = document.querySelector("form")
FormDataJson.fromJson(form, {communication:{
	preference:["email", "letter"]
}});
</script>

Array is expected

Describe the bug
I expect array for multiple values, but hash is returned

To Reproduce

<form>
	<input name = "docn">
	<input name = "docdate">

	<input name = "client[name]">
	<input name = "client[edrpou]">

	<input name = "client[phone][]">
	<input name = "client[phone][]">
	<input name = "client[phone][]">


	<input name = "client[email][]">
	<input name = "client[email][]">

	<select name="client[status][]" id="cars" multiple>
	  <option value="volvo">Volvo</option>
	  <option value="saab">Saab</option>
	  <option value="opel">Opel</option>
	  <option value="audi">Audi</option>
	</select>

	<input type="checkbox" name="scales[]" checked value="77">
	<input type="checkbox" name="scales[]">
</form>
FormDataJson.fillFormFromJsonValues($("form")[0], 
  {docn : 'asdf', docdate: 'addd', client: { name: 'asdf DDD', phone: [ 'zzzz', 'dd' ] } }, 
  new FormDataJsonOptions({ unsetAllInputsOnFill: true }) 
)

image

Elements out of order are processed incorrectly

HI! I`v got a little bit problem. When my input fields have names (index) out of order the hash is in wrong format.

<input type="hidden" name="Company[Phone][0][id]"         value="122"                   class="form-control" />
<input type="hidden" name="Company[Phone][0][phone]"  value="3339991111"     class="form-control" />

<input type="hidden" name="Company[Phone][2][id]"         value="125"                   class="form-control" />
<input type="hidden" name="Company[Phone][2][phone]"  value="33"                    class="form-control" />

Phone => {
      0 => {
        id => 122,
        phone => 3339991111,
      },
      2 => {
        id => 125,
        phone => 33,
      },

I dynamically add and delete fields so the situation is common. Maybe there is sense to use array without index (like additional opportunity to use the array). For method 'fromJson' use each next element without index binding.

<input type="hidden" name="Company[Phone][][id]"         value="122"                   class="form-control" />
<input type="hidden" name="Company[Phone][][phone]"  value="3339991111"     class="form-control" />

NPM Module?

Describe the bug
There's an npm install in the readme but can not import?

To Reproduce

import FormDataJson from "form-data-json-convert"
const FormDataJson2 = require("form-data-json-convert")

// both returns empty objects

Can not setup values to form

Describe the bug
this does not setup all form values, just client.name:

FormDataJson.fillFormFromJsonValues($("form")[0], {docn : 'asdf', docdate: 'addd', client: { name: 'asdf DDD'  } },
    new FormDataJsonOptions({ unsetAllInputsOnFill: true }) 
)

But this setup correct:

FormDataJson.fillFormFromJsonValues($("form")[0], {docn : 'asdf', docdate: 'addd', client: { name: 'asdf DDD'  } } ) 
)

To mine mind problem is when we go into nested data, then it clear outer form fields

setInputValue on checkboxes that have initial value false to true doesn't work.

Describe the bug
FormDataJson.setInputValue() seems to work like this in the case of checkboxes:

inputElement.checked = value === inputElement.value

So, if the initial value is false, then true === false would return false.

Expected behaviour

FormDataJson.setInputValue(input, true); should set the input value to true.

Actual behaviour

FormDataJson.setInputValue(input, true); sets the input value to false.

To Reproduce
https://codepen.io/schart/pen/gOaYOGQ

Proposed fix

Changing line 57 from

inputElement.checked = value === inputElement.value

to

inputElement.checked = value


Is this here on purpose, or is it a bug?

v2-dev: toJson return object instead of array:

Describe the bug

	<input name = "client[][phone][]">
	<input name = "client[][phone][]">
	<input name = "client[][phone][]">


	<input name = "client[][email][]">
	<input name = "client[][email][]">


	<input name = "client[][phone][]">
	<input name = "client[][phone][]">

	<input name = "client[][email][]">
	<input name = "client[][email][]">
	<input name = "client[][email][]">

To Reproduce

FormDataJson.toJson( $('form') )

image

Here I get 10 array elements as expected (green),
also first phone is pushed into array as expected, but next phone (second, third) are objects
first email is array as expected, but next email (second) is object

for second,third email/phone I expect arrays

**probably this example is meaningless, because this is unusual to create email, phone objects at separate array elements. They should be grouped together semantically. So for this case warning should be issued.

**despite on unusual naming objects are not expected, e.g. counter should be flushed, when [] is processing
To my mind it should be just command to push into array and counter should not have matter. For cases when it has matter developer will use explicit value: [1] or [7] etc. (see post below)

Trigger for 'onchange'

Is your feature request related to a problem? Please describe.
Hey! I am using the 'fromJson' method to set data to my form. And I have disabled fields. Fields filled by the 'onchange' event on some other fields. But when filling out the form with 'fromJson', 'onchange' doesn't fire.

Describe the solution you'd like
It would be usefull triger 'onchange' when we set data to Form programmatically.
In support of the popularity of this need, I provide a link:
https://stackoverflow.com/questions/3179385/val-doesnt-trigger-change-in-jquery

Typing of typescript Suggestion

First, congratz of your job.

I use with typescript and want suggest a little help to other people

declare module 'form-data-json-convert' {
	interface OptionsToJson {
	  includeDisabled?: boolean;
	  includeButtonValues?: boolean;
	  uncheckedValue?: any;
	  inputFilter?: ((inputElement: HTMLInputElement) => boolean) | null;
	  flatList?: boolean;
	  skipEmpty?: boolean;
	  filesCallback?: ((values: any) => void) | null;
	  fileReaderFunction?: string;
	  arrayify?: boolean;
	}
  
	interface OptionsFromJson {
	  flatList?: boolean;
	  clearOthers?: boolean;
	  resetOthers?: boolean;
	  triggerChangeEvent?: boolean;
	}
  
	function toJson(
	  form: HTMLFormElement | string | JQuery,
	  options?: OptionsToJson
	): any;
  
	function fromJson(
	  form: HTMLFormElement | string | JQuery,
	  values: any,
	  options?: OptionsFromJson
	): void;
  
	function reset(form: HTMLFormElement | string | JQuery): void;
  
	function clear(form: HTMLFormElement | string | JQuery): void;
  
	const defaultOptionsToJson: OptionsToJson;
	const defaultOptionsFromJson: OptionsFromJson;
  }

Ignore hidden fields

Is your feature request related to a problem? Please describe.
I'm using this library to store form data into localStorage as a "draft". But I don't want to store hidden fields, because I don't want to store passwords, nor csrf tokens.

Describe the solution you'd like
I would be able to add an option in formToJson method to don't get hidden fields in json result, like something like:

let values = FormDataJson.formToJson(document.querySelector("form"), new FormDataJsonOptions({ includeHidden: false }))

I guess the default value for includeHidden should be true in order to prevent BC break, and to keep the same behaviour for those who want to POST the json to a server, and need the hidden fields.

By the way, thanks for this vanillaJs library, which is not dependant to jquery, or is not a react/angular module !

Module parse failed: Unexpected token (15:30)

Describe the bug

Message:
    ./src/js/common/form-data-json.cjs 15:30
Module parse failed: Unexpected token (15:30)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
|    * @type {{}}
|    */
>   static defaultOptionsToJson = {
|     /**
|      * Include all disabled field values
 @ ./src/js/common/form-data-json-exposed.cjs 1:33-66
 @ ./src/js/modal.js
Details:
    domainEmitter: [object Object]
    domainThrown: false

To Reproduce
Unknown. Just upgraded from 2.1.3 to 2.1.4

Probably there is problem with my tooling, but there is no any notices about requirements at changelog.

Adding FormDataJsonOptions.defaults

Feature Request: #5

  • Test added in docs/tests/test.html
  • Updated minified version with npm run dist
  • Updated Changelog.md
  • Updated version in package.json
  • Created a new release
  • Published new NPM package with npm publish

Use `import` instead of `require`

Is your feature request related to a problem? Please describe.

import { FormDataJson as FormDataJson } from "form-data-json-convert/dist/form-data-json";

After this line of code FormDataJson stays undefined. Is this supported?

Describe the solution you'd like
Support modern way of module loading.

Document how to import this module

I download form-data-json.js into my package and try to import this module:

const FormDataJson = require('../common/form-data-json.js');

export function ajaxForm(form) {
  const formData  = FormDataJson.toJson( form );

But get error: FormDataJson is not defined

How to import this module?

how to skip non selected select option

I am using FormDataJson.toJson("#searchForm", {skipEmpty: true}), but I found that for select option:

<select name="gender">
	<option value="" selected></option>
	<option value="0" >Male</option>
	<option value="1" >Female</option>
</select>

if there is no valid option selected(that is Male or Female in this case), FormDataJson.toJson("#searchForm", {skipEmpty: true}) still return gender with null, what I suppose is to skip gender. I tried to change <option value="" selected></option> to <option ></option>, still not work.

how can I skip non selected select element?

Wouldn't it be nicer if toJSON returns promise

When converting form it could be take time to convert file fields. I think it would be better if toJson returns a promise so we can be sure that it worked 100% as we use it with toJson().then()

v2-dev: `skipEmpty` still includes empty arrays/objects

Describe the bug
When nested form fields are not filled, they are included anyway

To Reproduce

	<input name = "client[name]">
	<input name = "client[edrpou]">

	<input name = "client[person][0][phone][]">
	<input name = "client[person][0][phone][]">
	<input name = "client[person][0][phone][]">


	<input name = "client[person][0][email][]">
	<input name = "client[person][0][email][]">


	<input name = "client[person][1][phone][]">
	<input name = "client[person][1][phone][]">

	<input name = "client[person][1][email][]">
	<input name = "client[person][1][email][]">
	<input name = "client[person][1][email][]">
	<select name="client[status][]" id="cars" multiple>
	  <option value="volvo">Volvo</option>
	  <option value="saab">Saab</option>
	  <option value="opel">Opel</option>
	  <option value="audi">Audi</option>
	</select>

	<input type="checkbox" name="scales[]">
	<input type="checkbox" name="scales[]" checked value="77">

image

Add Input file read

  • Test added in tests/test.html
  • Updated minified version with npm run dist
  • Updated Changelog.md
  • Updated version in package.json
  • Created a new release
  • Published new NPM package with npm publish

Get empty value in the data if use field name with nesting (array)

Hi! I suppose I do not understand something.
I need data in format:

{
   _Company: {
      name: 'xxx',
      _Phone: [
        {
            phone: 3333,
        }
     ],
  },
}

The 'skipEmpty' is on 'true'.
When I used the code without nesting array the empty value (id) was not presented in data:
<input type="hidden" name="_Company[_Phone][id]" class="form-control" />

Now I use
<input type="hidden" name="_Company[_Phone][0][id]" class="form-control" />
and data has id: , with empty value. Why is that?

Conversion of a list of element[number] not done when a number is missing

Conversion of a list of element[number] not done when a number is missing
When the form contains inputs (e.g.) that want to become arrays in Json and these elements are not numbered properly (e.g. the bug happens if the element looks like this (see below) or contains no [0]).
Example :

input type="text" name="localisation[elementRoute][3][nom]" value="1945โ€“1986" />
input type="text" name="localisation[elementRoute][3][nombre]" value="1945โ€“1986" />

input type="text" name="localisation[elementRoute][2][nom]" value="1945โ€“1986" />
input type="text" name="localisation[elementRoute][2][nombre]" value="1945โ€“1986" />

input type="text" name="localisation[elementRoute][11][nom]" value="1945โ€“1986" />
input type="text" name="localisation[elementRoute][11][nombre]" value="1945โ€“1986" />

The result look like this :

{"localisation":{"elementRoute":{"3":{"nom":"1945โ€“1986","nombre":"1945โ€“1986"},"3":{"nom":"1945โ€“1986","nombre":"1945โ€“1986"},"2":{"nom":"1945โ€“1986","nombre":"1945โ€“1986"},"11":{"nom":"1945โ€“1986","nombre":"1945โ€“1986"}}

The result that 'I would like (or normally need to be) :

{"localisation":{"elementRoute":[{{"nom":"1945โ€“1986","nombre":"1945โ€“1986"},{"nom":"1945โ€“1986","nombre":"1945โ€“1986"},{"nom":"1945โ€“1986","nombre":"1945โ€“1986"}}]

It will be great if the "bug" will be fixed for less code (and more 'real' coding =) ).
Have a great day

Name syntax with dot

Hi! Now to specify nesting I have to use '[ ]' in field name.

Maybe It would be more convenient to use '.'
Example (something like this):

<input name="Company[Phone][0][phone]" type="text" value="34343">
<input name="Company.Phone[0]phone" type="text" value="34343">

Where the data is:

{
 Company: {
  Phone: [{
     phone: 34343,
   }],
 },
}

v2-dev: implement `resetOthers` similar to .reset/.clear methods

Is your feature request related to a problem? Please describe.
We have clear, reset methods:

FormDataJson.reset(document.querySelector("form"))
FormDataJson.clear(document.querySelector("form"))

But only one option: clearOthers

Describe the solution you'd like
Impelement resetOthers option for usage with FormDataJson.fromJson( ... )

FR: It seems excess to do `new FormDataJsonOptions`

It seems too verbose to write each time: new FormDataJsonOptions.
To pass values we could just pass a simple hash. If this is required by code then this hash could be turned into FormDataJsonOptions internally

also these methods fillFormFromJsonValues, formToJson could be simplified to: fillForm, readForm
or toForm, toJson. Is there any reason for long typing?

unsetAllInputsOnFill -> clearForm.
+implement resetForm. Different is that clearForm - clears all inputs, resetForm set default form values if there is not corresponding value at supplied hash.

Thank you

Implement FormDataGraphQL

Is your feature request related to a problem? Please describe.
Hi. We have complex forms. For example Company have multiple emails, phones. While we can send this at object like:

{ Company => { name => 'x', phones => [{ phone => '1234' },{ phone => '12345' }], emails => [{...},{...}] } }

We want to do same thing via GraphQL

It would be nice if FormDataJson will be able to send this data at GraphQL format

Describe the solution you'd like
https://graphql.org/

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.