Created
May 22, 2019 18:25
-
-
Save mspreij/28b908c351f5de62837f914e624478c3 to your computer and use it in GitHub Desktop.
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
// based on: https://github.com/scottaohara/select-to-datalist/blob/master/assets/js/progressive-datalist.js | |
// changes select to input with datalist, that thing where you type and it suggests matching entries | |
function selectToDatalist(element) { | |
// todo: accept actual element instead of selector string | |
var select = document.querySelector(element); | |
if (select.tagName != 'SELECT') { | |
console.error('not a select: '+ element); | |
return false; | |
} | |
var grabOptions = select.innerHTML; | |
var curValue = select.value; | |
// create new input and grab attributes from select | |
var genID = 'datalist_' + Math.floor(Math.random() * 999) + 1; // ¯\_(ツ)_/¯ | |
var newInput = document.createElement('input'); | |
newInput.setAttribute('type', 'text'); | |
newInput.setAttribute('list', genID); | |
newInput.value = curValue; | |
for (var a = 0; a < select.attributes.length; a++) { | |
var attr = select.attributes.item(a); | |
newInput.setAttribute(attr.nodeName, attr.nodeValue); | |
} | |
// create new datalist. Set its ID, and pull the original select element's options into the new element | |
var newDatalist = document.createElement('datalist'); | |
newDatalist.setAttribute('id', genID); | |
newDatalist.innerHTML = grabOptions; | |
// it's not possible to reliably copy an element's eventhandlers, so instead of replacing the select we | |
// just hide it, and trigger a change on it when the newInput element was changed. | |
newInput.addEventListener('change', function () { | |
select.value = newInput.value; | |
var event = new Event('change'); | |
select.dispatchEvent(event); | |
}); | |
// add the input & datalist after select, and hide select | |
select.insertAdjacentElement('afterend', newInput); | |
newInput.insertAdjacentElement('afterend', newDatalist); | |
select.style.display = 'none'; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment