In order to get all selected options from multiple select box we have to create custom function which will be triggered on change event.
So first we will create JS function to get all multiple select values:
So first we will create JS function to get all multiple select values:
function getMultipleSelected(fieldID){ // fieldID is id set on select field // get the select element var elements = document.getElementById(fieldID).childNodes; // if we want to use key=>value of selected element we will set this object var selectedKeyValue = {}; // if we want to use only array of selected values we will set this array var arrayOfSelecedIDs=[]; // loop over option values for(i=0;i<elements.length;i++){ // if option is select then push it to object or array if(elements[i].selected){ //push it to object as selected key->value selectedKeyValue[elements[i].value]=elements[i].textContent; //push to array of selected values arrayOfSelecedIDs.push(elements[i].value) } } // output or do seomething else with these values :) console.log(selectedKeyValue); console.log(arrayOfSelecedIDs); }
And here we will create HTML select element calling this function
<select onchange="getMultipleSelected(this.id)" multiple="multiple" name="languages[]" id="languages"> <option value="1">Afrikaans</option> <option value="2">Albanian</option> <option value="3">Amerindian</option> <option value="4">Arabic</option> <option value="5">Armenian</option> <option value="6">Bahasa Indonesia</option> </select>