Search code examples
javascripthtmlcomboboxhtml-select

how to get multiple selected values and items from listbox using javascript


    <!DOCTYPE html>
    <html>
    <script>
    function getValue()
    {
      var x = document.getElementById("sel");
      for (var i = 0; i < x.options.length; i++) {
          if (x.options[i].selected == true) {
              alert(x.options[i].selected);
          }
      }
    }
    </script>
    </head>
    <body>
    <select multiple="multiple" id="sel">
      <option value="volvo">Volvo</option>
      <option value="saab">Saab</option>
      <option value="opel">Opel</option>
      <option value="audi">Audi</option>
    </select>
    <input type="button" value="Get Value" onclick="getValue()"/>
    </body>
    </html>

This is my code. How do I get all the selected values from a listbox using JavaScript? The above code is showing true for all the selected values.


Solution

  • Replace

      if(x.options[i].selected ==true){
          alert(x.options[i].selected);
      }
    

    with

      if(x.options[i].selected){
          alert(x.options[i].value);
      }