Obtaining select values in JS

I have a <select> element with the multiple attribute. How can I get this element’s selected values using JavaScript?

Here’s what I’m trying:

function loopSelected() { 
    var txtSelectedValuesObj = document.getElementById('txtSelectedValues');
    var selectedArray = new Array();
    var selObj = document.getElementById('slct'); 
    var i;
    var count = 0;
    for (i=0; i<selObj.options.length; i++) { 
        if (selObj.options[i].selected) {
            selectedArray[count] = selObj.options[i].value;
            count++; 
        } 
    } 
    txtSelectedValuesObj.value = selectedArray;
}

The form supplies access to all elements via the form.elements object.
The name attribute is the most effective way to access form elements.

function showResult(count) {
  ...
}

const form = document.querySelector("#countSelected");
form.addEventListener("change", function countSelectedHandler(evt) {
  const elements = form.elements;
  const options = elements.ordinalNumbers.options;
  const isSelected = (option) => option.selected;
  const count = Array.from(options).filter(isSelected).length;
  showResult(count);
});

See it in action at https://jsfiddle.net/pmw57/zb784kgw/

2 Likes

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.