Skip to content

Instantly share code, notes, and snippets.

@greyaperez
Last active November 22, 2017 04:14
Show Gist options
  • Save greyaperez/593b0709d55047ef98c4f7cfdd672014 to your computer and use it in GitHub Desktop.
Save greyaperez/593b0709d55047ef98c4f7cfdd672014 to your computer and use it in GitHub Desktop.
Get collection of label / value from form select element.
// Pure JavaScript
function selectToCollection(selector, asJson) {
var options = Array.from(document.querySelector(selector).querySelectorAll('option'));
var collection = options.reduce((prev, curr) => {
return [...prev, { label: curr.label, value: curr.value}];
}, []);
return (asJson === true) ? JSON.stringify(collection) : collection;
}
// With jQuery
function selectToCollection(selector, asJson) {
var collection = $(selector).find('option').toArray().reduce((prev, curr) => {
return [...prev, { label: curr.label, value: curr.value}];
}, []);
return (asJson === true) ? JSON.stringify(collection) : collection;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment