title: Set Selected Indices in Multi Select Using Javascript
body: <p>Im not sure why this isnt working and would love some help with it!  And yes i have looked at <a href="https://stackoverflow.com/questions/4957493/how-do-i-programatically-set-the-values-plural-of-a-multi-select-box-element-u">this</a></p>
  
  <p>Im trying to set multiple options in a select element as selected using an array holding the values i want selected and interating through both the array and the options in the select element.    Please find code below:</p>
  
  <pre><code>// value is the array.
  for (var j = 0; j &lt; value.length; j++) {
      for (var i = 0; i &lt; el.length; i++) {
          if (el[i].text == value[j]) {
              el[i].selected = true;
              alert("option should be selected");
          }
      }
  }
  </code></pre>
  
  <p>After completing these loops nothing is selected, even though the alert() fires.</p>
  
  <p>Any ideas are welcome!</p>
  
  <p>Thanks</p>
  
  <p>CM</p>
  
  <p>PS (not sure whats happened to the code formatting).</p>
  
  <p>EDIT: Full function</p>
  
  <pre><code>    if (CheckVariableIsArray(value) == true) {
          if (value.length &gt; 1) { // Multiple selections are made, not just a sinle one.
              var checkBoxEl = document.getElementById(cbxElement);
              checkBoxEl.checked = "checked";
              checkBoxEl.onchange(); // Call function to change element to a multi select
              document.getElementById(element).onchange(); // Repopulates elements with a new option list.
              for (var j = 0; j &lt; value.length; j++) {
                  for (var i = 0; i &lt; el.length; i++) {
                      if (el[i].text === value[j]) {
                          el[i].selected = true;
                          i = el.length + 1;
                      }
                  }
              }
              //document.getElementById(element).onchange();
          }
      }
      else {
          for (var i = 0; i &lt; el.length; i++) {
              if (el[i].innerHTML == value) {
                  el.selectedIndex = i;
                  document.getElementById(element).onchange();
              }
          }
      }
  </code></pre>