Last active
November 22, 2017 04:14
-
-
Save greyaperez/593b0709d55047ef98c4f7cfdd672014 to your computer and use it in GitHub Desktop.
Get collection of label / value from form select element.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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