Created
July 17, 2019 04:44
-
-
Save shovon/75c95cedfb12b7eb55258a68b7f1ad51 to your computer and use it in GitHub Desktop.
Convert multi-select to checkboxes
This file contains 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
const form = document.getElementById('form'); | |
const multiSelects = [...form.querySelectorAll('select')] | |
.filter(el => el.multiple); | |
function *indexedIteration(iterable) { | |
let count = 0; | |
for (const item of iterable) { | |
yield [ item, count ]; | |
count++; | |
} | |
} | |
const convertSelectBox = (select, uniqueSelectID = '0') => { | |
select.hidden = true; | |
const container = document.createElement('div'); | |
for (const [ option, index ] of indexedIteration(select.options)) { | |
const checkboxContainer = document.createElement('div'); | |
const uniqueID = `${uniqueSelectID} ${index}`; | |
const checkbox = document.createElement('input'); | |
checkbox.id = uniqueID; | |
checkbox.type = 'checkbox'; | |
checkbox.addEventListener('change', (e) => { | |
select.options[index].selected = e.target.checked; | |
}); | |
const label = document.createElement('label'); | |
label.innerText = option.text; | |
label.setAttribute('for', uniqueID); | |
checkboxContainer.appendChild(checkbox); | |
checkboxContainer.appendChild(label); | |
container.appendChild(checkboxContainer); | |
} | |
select.parentNode.insertBefore(container, select); | |
}; | |
for (const [ select, count ] of indexedIteration(multiSelects)) { | |
convertSelectBox(select, count); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment