I have a multi-select form field that is populated from a database query. I would like all of the options selected by default. Is that possible?
Basically I have a query that can return up to three results. I would like to add the values of those results into a single database field as a comma separated string. Maybe there is a better way?
ChatGPT to the rescue! I will leave the solution here for others.
<script>
// Get the select element
var select = document.getElementById("mySelect");
// Set the 'selected' property of each option to true
for (var i = 0; i < select.options.length; i++) {
select.options[i].selected = true;
}
</script>
In the example above, the select variable is assigned to the <select> element with the ID “mySelect”. The JavaScript code then iterates over each option within the select element and sets the selected property of each option to true .
By executing this code when the page loads or at an appropriate event, all options within the multi-select field will be selected by default.
Remember to place the script after the HTML code for the select element or wrap it in an event listener to ensure that the DOM elements are available before modifying them.