I have two selectboxes that will each have the same values in both selectboxes. I’m trying to perform the following action:
If a user selects an option with the value of "red", disable the "red" option in the other selectbox, and enable it if a user selects a different color.
I’m able to get the disabled attribute to work, but I can’t figure out how to "un-disable" it after a user selects a different option.
const preventDuplicate = (e) => {
if (!e.target == "select-one") return; // Bail if not a selectbox
const selectOne = document.querySelector("#one");
const selectTwo = document.querySelector("#two");
const getValue = () => e.target.value;
if (e.target == selectOne) {
// Get the value
const value = getValue();
// Get the other selectbox value
const otherValue = selectTwo.querySelector(`[value="${value}"]`);
// Disable it
if (otherValue) {
otherValue.setAttribute("disabled", "disabled");
} else {
otherValue.removeAttribute("disabled");
}
} else {
// Get the value
const value = getValue();
// Get the other selectbox value
const otherValue = selectOne.querySelector(`[value="${value}"]`);
// Disable it
if (otherValue) {
otherValue.setAttribute("disabled", "disabled");
} else {
otherValue.removeAttribute("disabled");
}
}
};
document.addEventListener("change", preventDuplicate);
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<div class="selectbox-container">
<label for="one">Select One</label>
<select name="" id="one">
<option value="red">Red</option>
<option value="green">Green</option>
<option value="blue">Blue</option>
<option value="teal">Teal</option>
</select>
<label for="two">Select Two</label>
<select name="" id="two">
<option value="red">Red</option>
<option value="green">Green</option>
<option value="blue">Blue</option>
<option value="teal">Teal</option>
</select>
</div>
</body>
</html>
2
Answers
Thanks for all the replies - I ended up going with @mykaf suggestion and wrote the following, which worked well:
With your permission, I changed your code and wrote only for
selectBoxOne
as you saidI think this code is a bit cleaner
Also the same code is repeated for
selectBoxTwo
I hope it has been used