'Use <select> in Twig / Timber
I have the following code in a .twig WordPress template:
<select id="filter-assessment-year">
<option disabled selected hidden>ASSESSMENT YEAR</option>
<optgroup label="Assessment Year">
<option value="2022">2022 Assessment</option>
<option value="2021">2021 Assessment</option>
<option value="2020">2020 Assessment</option>
<option value="2019">2019 Assessment</option>
</optgroup>
</select>
I then need to output different code depending on which year the user selects. I want to basically say if user selects 2022 then output this code, else if user selects 2021 then output this code.
How can I use the above option selection to control the code output in my twig template?
Thank you
Solution 1:[1]
You would need to use javascript for this. Try a library like Alpine JS if you're not already using jQuery.
const selectForm = document.getElementById('assesment');
selectForm.addEventListener("change", function(){
if(selectForm.value === '2022'){
alert('2022 Code will run');
}
if(selectForm.value === '2021'){
alert('2021 Code will run');
}
if(selectForm.value === '2020'){
alert('2020 Code will run');
}
if(selectForm.value === '2019'){
alert('2019 Code will run');
}
});
<form>
<select id="assesment" class="target">
<option value="0">ASSESSMENT YEAR</option>
<option value="2022">2022 Assessment</option>
<option value="2021">2021 Assessment</option>
<option value="2020">2020 Assessment</option>
<option value="2019">2019 Assessment</option>
</select>
</form>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
