Given this HTML:
<select id="leaveCode" name="leaveCode">
<option value="10">Annual Leave</option>
<option value="11">Medical Leave</option>
<option value="14">Long Service</option>
<option value="17">Leave Without Pay</option>
</select>
How do you write a JavaScript function that takes a leave code number as a parameter and sets the corresponding option as selected in the element? What’s the best approach to use javascript set selected option effectively here?
Hey! From my experience, the simplest way to javascript set selected option on a <select>
is just to grab the element and assign the .value
property directly. Here’s a quick function:
function setLeaveCode(code) {
const select = document.getElementById('leaveCode');
select.value = code;
}
This works great because if the value exists among the options, the select will update automatically. If the value isn’t found, it just won’t select anything, so it’s pretty straightforward and clean.
That’s a solid start! To add a bit more robustness when you want precise control over javascript set selected option, you might want to loop through the options and set the .selected
property explicitly. This way, you can also handle cases where the code might not exist and give a warning:
function setLeaveCode(code) {
const select = document.getElementById('leaveCode');
let found = false;
for (let option of select.options) {
if (option.value === String(code)) {
option.selected = true;
found = true;
break;
}
}
if (!found) {
console.warn(`Leave code ${code} not found in options`);
}
}
This approach is handy if you want to be sure the option is selected and have feedback when the value is missing. It’s a bit more explicit than just setting .value
.
Nice points so far! If you want to keep things modern and concise, while still doing effective javascript set selected option, you can combine the best of both worlds using querySelector
with arrow functions. It’s minimal, readable, and instantly updates the UI:
const setLeaveCode = code => {
const select = document.querySelector('#leaveCode');
select.value = code;
};
This leverages the native behavior of <select>
elements and keeps your code neat. Just keep in mind, if the value doesn’t exist, it won’t select anything, but for most cases, this simple method is both clean and efficient.