Working With Select Elements
Fire the Change event
document.getElementById('mySelect').dispatchEvent(new Event('change));
Get Values of Selected Options
const selectedValuesArray = [...document.getElementById('mySelect').selectedOptions].map(x => x.value);
Get Values of Selected Options as CSV
const selectedValuesArray = [...document.getElementById('mySelect').selectedOptions].map(x => x.value).join();
Populate and filter by table cell content
// reference select element
const advertTypeSelector = advertTypeWrapper.querySelector('select');
// add a change event handler, passing the selector as an argument
advertTypeSelector?.addEventListener('change', () => filterByType(advertTypeSelector));
// reference the relevant table cells
const adverts = results.querySelectorAll('td.advert') as NodeListOf<HTMLTableCellElement>;
// if there are any, create a Set (like a HashSet in C# - does not permit duplicate values) out of their contents (trimmed)
// clear the selector options, add a blank one and then new ones based on the content of the Set
if (adverts.length) {
advertTypeSelector.replaceChildren();
const advertOptions = new Set([...adverts].map(x => x.textContent.trim()).sort());
advertTypeSelector.append(new Option());
advertOptions.forEach(option => advertTypeSelector.append(new Option(option, option)));
advertTypeWrapper.reveal();
}
else {
advertTypeWrapper.conceal();
}
// show all rows to start, then toggle d-none based on the selected value, if there is one
const filterByType = (selector:HTMLSelectElement) => {
const advertTypes = results.querySelectorAll('td.advert') as NodeListOf<HTMLTableCellElement>;
advertTypes.forEach(x => x.closest('tr').reveal());
advertTypes.forEach(x => x.closest('tr').classList.toggle('d-none', selector.value && x.textContent.trim() !== selector.value.trim()));
}