Tuesday, May 28, 2024
 Popular · Latest · Hot · Upcoming
42
rated 0 times [  44] [ 2]  / answers: 1 / hits: 16562  / 12 Years ago, tue, november 20, 2012, 12:00:00

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.....



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.



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.



EDIT



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: http://harvesthq.github.com/chosen/



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.



function selectitems() {
var select = document.getElementById(multiselectid);
var array = stringFromDB.split(,);

for(count=0, count<array.length, count++) {
for(i=0; i<select.options.length; i++) {
if(select.options[i].value == array[count]) {
select.options[i].selected=selected;
}
}
}
}

More From » javascript

 Answers
66

Your first for loop has two syntax errors. Try checking the console in your browser



for(count=0, count<array.length, count++) {


should be:



for(count=0; count<array.length; count++) {


Notice the change of , to ; after the count=0 and count<array.length parts.



Also, you might want to use for(var count=0 and for(var i=0 so that the count and i variables are not declared globally.


[#81901] Sunday, November 18, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
harleyterryp

Total Points: 290
Total Questions: 92
Total Answers: 95

Location: Montenegro
Member since Sun, May 7, 2023
1 Year ago
;