Skip to content

Instantly share code, notes, and snippets.

@shovon
Created July 17, 2019 04:44
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 shovon/75c95cedfb12b7eb55258a68b7f1ad51 to your computer and use it in GitHub Desktop.
Save shovon/75c95cedfb12b7eb55258a68b7f1ad51 to your computer and use it in GitHub Desktop.
Convert multi-select to checkboxes
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