@sharyn/browser.getformdata
TypeScript icon, indicating that this package has built-in type declarations

1.0.4 • Public • Published

🌹 getFormData

getFormData: Gives you the fields and data of a form element. getFormData uses FormData and returns a plain object.

Installation

npm i @sharyn/browser.getformdata
# or
yarn add @sharyn/browser.getformdata

You can alternatively install the @sharyn/browser package, or the entire sharyn library.

Arguments

formElement (HTMLFormElement): The HTML form element.

[onlyTruthy=false] (boolean): Falsy fields (like '') are omitted if true.

Returns

object: The plain object of the form data.

Example

const Form = () => {
  const form = useRef(null)
  return (
    <>
      <form ref={form}>
        <input name="firstname" />
        <input name="lastname" />
      </form>
      <button onClick={() => console.log(getFormData(form.current))}>
        Log all form values
      </button>
      <button onClick={() => console.log(getFormData(form.current, true))}>
        Log truthy form values
      </button>
    </>
  )
}

If firstname is Stan and lastname is left empty:

getFormData(form.current)       // { firstname: 'Stan', lastname: '' }
getFormData(form.current, true) // { firstname: 'Stan' }

Imports

Depending on the package you are using, you can import or require getFormData in the following ways:

// If you installed @sharyn/browser.getformdata
import getFormData from '@sharyn/browser.getformdata' // smaller size, better for client bundles

// If you installed @sharyn/browser
import getFormData from '@sharyn/browser/getFormData' // smaller size, better for client bundles
import { getFormData } from '@sharyn/browser' // more convenient in Node environments

// If you installed sharyn
import getFormData from 'sharyn/browser/getFormData' // smaller size, better for client bundles
import { getFormData } from 'sharyn/browser' // more convenient in Node environments

This package is part of Sharyn, a collection of utilities and helpers.

Package Sidebar

Install

npm i @sharyn/browser.getformdata

Weekly Downloads

1

Version

1.0.4

License

MIT

Unpacked Size

5.28 kB

Total Files

5

Last publish

Collaborators

  • sharyn