Search code examples
javascriptphphtml-selectselected

Cycle through <select> / <option> list and collect values with PHP and JavaScript?


I have a set of <option> inside a <select> and want to use JavaScript to remove all values that have been selected, put them into a string then post it to my PHP script.


Solution

  • Using only Javascript/DOM I'm guessing the select has multiple attribute

    var selectElem = document.getElementById( 'myselect'); // your select element
    var strSelection = ''; // string to store the selected stuff
    for( let count = 0, limit = selectElem.options.length; count < limit; count++) //check every option
         if( selectElem.options[count].selected) // check if it's selected
             strSelection += selectElem.options[count].value + ','; // Concat to string and add delimiter, string format is up to you, here i add the .value but could also be .text or both..
    selectElem.selectedIndex = -1; //Resets the selection element so all options are unselected