I have a form with a select box that allows multiple options. After a user saves these options, it stores them in a database table.
I can then read this database table to get the options they chose one again. I need to be able to grab this data from the database, put it into an array, then have the options in that select box to be pre-selected when they go to "Edit" their options.
Reading the data into an array is fine, and I know how to make a single option selected within a select box, however I'm not sure how to handle multiple options being selected in javascript.
Can someone help me figure out the javascript required to do this?
This type of thing should be done server-side, so as to limit the amount of resources used on the client for such trivial tasks. That being said, if you were to do it on the front-end, I would encourage you to consider using something like underscore.js to keep the code clean and concise:
If you're using jQuery, it could be even more terse:
If you were to do this without a tool like underscore.js or jQuery, you would have a bit more to write, and may find it to be a bit more complicated:
A pure javascript solution
Although I agree this should be done server-side.
You can get access to the options array of a selected object by going
document.getElementById("cars").options
where 'cars' is the select object.Once you have that you can call
option[i].setAttribute('selected', 'selected');
to select an option.I agree with every one else that you are better off doing this server side though.
Based on @Peter Baley answer, I created a more generic function:
Example:
checkMultiValues('thisMultiHTMLObject','a,b,c,d');