Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to set the selected options in multiselect with javascript
    text
    copied!<p>Alright, so this question has definitely been asked before, and I was actually able to find an answer to my question in jquery and when I tried to implement the answer I couldn't get it to work. I would just rather do it in java-script so.....</p> <p>I'm reading a string of text separated by commas from a DB, and I want to translate those into selected options in a multiselect box.</p> <p>All I've been doing up to this point is trying to get the browser to select a single option which matches a hard-coded string when I click a button but I can't even get that to work. But I figured that since I'm asking the question, I might as well write out the whole script so you can see it all and maybe catch any other problems I can expect to have...lastly, how can I get this to run on the page's load? Sorry if this is redundant and rudimentary but I'm very new to JS and finding existing answers to questions to be of little help. Thanks in advance.</p> <p><strong>EDIT</strong></p> <p>So, I found that I can get the assignment to work if I use 'select.options[i].value=true' (boolean instead of string) per Asad's answer. However, I am using Harvest's Chosen multiple select control: <a href="http://harvesthq.github.com/chosen/" rel="noreferrer">http://harvesthq.github.com/chosen/</a></p> <p>The script will not work when I have assigned the chosen class to the control. I know that the control is calling on JQuery, is this the reason why? Is it possible to get it to work? Thanks again.</p> <pre><code>function selectitems() { var select = document.getElementById("multiselectid"); var array = stringFromDB.split(","); for(count=0, count&lt;array.length, count++) { for(i=0; i&lt;select.options.length; i++) { if(select.options[i].value == array[count]) { select.options[i].selected="selected"; } } } } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload