Skip to content

Instantly share code, notes, and snippets.

@Oaphi
Last active February 9, 2021 00:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Oaphi/f3a9460da865746e9b131d6274b850c5 to your computer and use it in GitHub Desktop.
Save Oaphi/f3a9460da865746e9b131d6274b850c5 to your computer and use it in GitHub Desktop.
Useful utilities for HTMLSelectElement
/**
* @summary extracts values from select
* @param {HTMLSelectElement} sel
* @return {string[]}
*/
const getSelectVals = ({ options }) =>
Array.from(options).map(({ value }) => value);
/**
* @summary checks if select has a value
* @param {HTMLSelectElement} sel
* @param {(val: string, idx: number) => boolean} predicate
* @return {boolean}
*/
const hasSelectVal = ({ options }, predicate) => {
return !!Array.from(options).find(({ value }, idx, thisArr) =>
predicate(value, idx)
);
};
/**
* @summary sets selected values in a select
* @param {HTMLSelectElement}
* @param {string[]} values
* @return {void}
*/
const selectVals = ({ options }, values) => {
return Array.from(options).forEach(
(option) => (option.selected = values.includes(option.value))
);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment