I have a form - which allows the user to select an option from a dropdown
<form action="/create_tasks/" name="form2" , id="form2" method="post" class="row row-cols-lg-auto g-3 align-items-center">
<input type="hidden" name="csrfmiddlewaretoken" value="F9Xrs4SIcjDS3yVMCH1hbAB1p3encpExp14ynCZV5jsDgjcD41qFoVeDn4wtpGr8">
<div class="col-12">
<label class="visually-hidden" for="inlineFormSelectPref">Preference</label>
<select class="form-select" id="inlineFormSelectPref">
<option selected value='all'>All </option>
<option value=SQL>SQL</option>
<option value=Apache Spark>Apache Spark</option>
<option value=Python>Python</option>
<option value=Linux>Linux</option>
</select>
</div>
<div class="col-12">
<button type="submit" class="btn btn-primary">filter</button>
</div>
</form>
I have divs underneath like this:
<div class="card mb-2 sh-10 sh-md-8 Python ">
</div>
<div class="card mb-2 sh-10 sh-md-8 Python ">
</div>
If the user selects a value from the dropdown, i want to only show the divs with that class (e.g. select Python , only show python divs). If they select 'all' I want to show them all
I had a play with some options but i cant make it work. Can anyone point me in the right direction please?
You can add input event listener on your select field. This will trigger every time you change option in your select. When this event trigger, simply read select value and show divs accordingly.
const select = document.getElementById('select');
const showSelected = name => {
document.querySelectorAll('.form-option').forEach(card => {
card.style.display = name === 'all' ? 'block' : 'none';
if (name !== 'all' && card.classList.contains(name.replace(' ', '-'))) {
card.style.display = 'block';
}
});
}
showSelected('all');
select.addEventListener('input', () => {
showSelected(select.value);
});
<select id="select">
<option selected value='all'>All</option>
<option value="SQL">SQL</option>
<option value="Apache Spark">Apache Spark</option>
<option value="Python">Python</option>
<option value="Linux">Linux</option>
</select>
<div class="form-option SQL">SQL</div>
<div class="form-option Apache-Spark">Apache Spark</div>
<div class="form-option Python">Python</div>
<div class="form-option Linux">Linux</div>