skip to Main Content

Context

<!--HTML-->
<select class="form-select mb-1" id="document-select" name="documents" multiple size="10">                                        
    <option class="document-option" value="1">20230308-seed-document-0</option>
    <option class="document-option" value="2">20230308-seed-document-1</option>
// JS
const documentSelectEl = document.getElementById("document-select");
form.addEventListener("submit", (event) => {
    documentSelectEl.selectedIndex = -1;
    documentSelectEl.value = ["1", "2"];
    console.log(documentSelectEl.value); // Empty string
    documentSelectEl.value = "1,2";
    console.log(documentSelectEl.value); // Empty string
}

Issue

I am trying to set the value of a select html element before form submission. My intention is to reset all selected option elements (documentSelectEl.selectedIndex = -1) – essentially ignoring them – and set the value of the select element directly.

The reason I am trying to achieve this is that the list of option elements is paginated. In other words, the currently selected set of option elements does not correspond to the full selection of the user.

I would like to pass the full set of selected values, which is retrieved from sessionStorage, either as an array or as a comma-separated string.

Neither of these options seem to work. I should note that looking at the value of the select element in the debugger, I always see a single value despite the multiple attribute. The value seems to correspond to the last selected option element. Does it mean that the only way to set the value of a select element with multiple attribute programmatically is by setting the desired option elements?

2

Answers


  1. Chosen as BEST ANSWER

    I solved it this way for the moment:

    // JS
    function setSelectedOptions(selectElement, values) {
        values.forEach(value => {
            const option = document.createElement("option");
            option.value = value;
            option.selected = true;
            selectElement.appendChild(option);
        });
    }
    

    Still curious whether a more direct approach is possible.


  2. Try this:

    const documentSelectEl = document.getElementById("document-select");
    const selectedValues = ["1", "2"]; 
    
    form.addEventListener("submit", (event) => {
        documentSelectEl.selectedIndex = -1; // Reset all selected options
    
        // Set selected options based on selectedValues
        const options = documentSelectEl.options;
        for (let i = 0; i < options.length; i++) {
            const option = options[i];
            option.selected = selectedValues.includes(option.value);
        }
    
        console.log(documentSelectEl.value); // Array of selected values
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search