Skip to content

Commit

Permalink
Created new setFormFieldValue method that replaces the `selectInput…
Browse files Browse the repository at this point in the history
…Element` one.
  • Loading branch information
alexiglesias93 committed Oct 27, 2021
1 parent 165e7dc commit 095d015
Show file tree
Hide file tree
Showing 4 changed files with 37 additions and 1 deletion.
1 change: 1 addition & 0 deletions helpers/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ export { queryElement } from './queryElement';
export { removeChildElements } from './removeChildElements';
export { removeSpaces } from './removeSpaces';
export { selectInputElement } from './selectInputElement';
export { setFormFieldValue } from './setFormFieldValue';
export { simulateEvent } from './simulateEvent';
export { throwError } from './throwError';
export { wait } from './wait';
3 changes: 3 additions & 0 deletions helpers/selectInputElement.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
import { simulateEvent } from './simulateEvent';

/**
* **DEPRECATED: Please use the new `setFormFieldValue` method instead.**
*
*
* Selects a custom radio or checkbox element
* @param element Element to select
* @param select - Defaults to true. If set to false, the input element will be unselected.
Expand Down
32 changes: 32 additions & 0 deletions helpers/setFormFieldValue.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import { simulateEvent } from '.';

import type { FormField } from '..';

/**
* Sets a value to a FormField element and emits `click`, `input` and `change` Events.
*
* @param element The FormField to update.
* @param value `boolean` for Checkboxes and Radios, `string` for the rest.
*/
export const setFormFieldValue = (element: FormField, value: string | boolean): void => {
const { type } = element;

if (typeof value === 'boolean') {
if (
!(element instanceof HTMLInputElement) ||
(type !== 'radio' && type !== 'checkbox') ||
(type === 'checkbox' && value === false) ||
value === element.checked
)
return;

element.checked = value;
} else {
if (type === 'radio' || type === 'checkbox' || element.value === value) return;

element.value = value;
}

// Emit DOM events
simulateEvent(element, ['click', 'input', 'change']);
};
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@finsweet/ts-utils",
"version": "0.19.0",
"version": "0.20.0",
"description": "Typescript utils for custom Webflow projects.",
"main": "index.ts",
"module": "index.ts",
Expand Down

0 comments on commit 095d015

Please sign in to comment.