In my Flask app, I have a page with 5 selectbox:
<select onchange="disableBtn()" id="first" name="select_first">
<option value="option1">Select an option</option>
{% for each in list %}
<option value="{{each}}">{{each}}</option>
{% endfor %}
</select>
I would like to enable/disable the button if only one of the selectbox has an option selected.
function disableBtn() {
var select = document.getElementById("first");
var selectedValue = select.options[select.selectedIndex].value;
if (selectedValue == "option1") {
document.getElementById("button").disabled = true;
} else {
document.getElementById("button").disabled = false;
}
}
How could I use the same function for all the boxes? I tried with multiple if but it works only for the first.
You can add a listener for the change event to all select elements, which checks whether an acceptable option was selected for one of the select boxes.
With querySelectorAll you query all select boxes.
With some you iterate over an array and check if a condition is true for at least one element.
const buttonElem = document.getElementById('button');
const selectElems = Array.from(document.querySelectorAll('select[name^="select_"]'));
selectElems.forEach(elem => {
elem.addEventListener('change', evt => {
buttonElem.disabled = !selectElems.some(e => e.value !== 'option1');
});
});
If the button should only be activated if exactly one select box was selected, the code is as follows.
window.addEventListener('DOMContentLoaded', () => {
const buttonElem = document.getElementById('button');
const selectElems = Array.from(document.querySelectorAll('select[name^="select_"]'));
selectElems.forEach(elem => {
elem.addEventListener('change', evt => {
buttonElem.disabled = selectElems.filter(e => e.value !== 'option1').length !== 1;
});
});
});
All select boxes are filtered for which "option1" was not selected. If the length of the resulting array is not one, the button is disabled.
The code is embedded in a listener that waits until the entire document is loaded.