jQuery MultiSelect

Interesting issue the past couple of days. I’ve been using the jQuery multiselect for a project that I’ve been working on the last couple of days. Getting the multiselect to display the values and names was the easy part. I had issues however when I wanted to update the form and show the previously selected options in the multiselect. The values get stored in the a data base column as 0,1,2,3,4
 
This was all coming from a JSON return which was rendering the info on screen, not sure that really matters with the issue I was having or not but it’s worth a mention.
 
$(“#selectboxname option[value='+ selectboxname +']").attr('selected', 'selected');
 
Initially I returned the above values but the box would be just black so I did a little research and came across a way that works
 

for(var i =0; i < NewMedium.length; i++){

//console.log("i = " +NewMedium.length);

$("#selectboxname").multiselect("widget").find(":checkbox[value='"+ NewMedium[i]+"']").attr("checked", "checked");

$("#selectboxname option[value='"+ NewMedium[i]+"']").attr("selected", 1);

$("#selectboxname").multiselect("refresh");

//console.log(NewMedium[i]);

}

I thought I was finished until I tested it with just one value was stored in the database would display nothing in the selectbox and and error would also get thrown. NewMedium.length is undefined. Which with that error getting thrown it would screw up the rest of my page and make me worry that a whole lot of other things were broken as well.
 

The Fix

what I initially did was add this block of code before the for loop. In the else statement is just set medium (which is  a JSON return value) to var NewMedium. While that got my rid of my javascript error or NewMedium is undefined it didn’t populate my multiselect. what I had to do was cheat a little adding the comma back to the end of medium.
 
if(medium.length >1){ 

var NewMedium = medium.split(',');

//console.log("1st if state " + NewMedium);

}else{

var NewMedium = medium;

//console.log("in else state " + NewMedium);

}

 
Not sure if this is the best way to get my multidisplay to work; But hell it works so who cares.
 

Finial Code 

 

if (medium.length > 1 ){ 

var NewMedium = medium.split(',');

//console.log("1st if state " + NewMedium);

}else{

var NewMedium = medium+",";

//console.log("in else state " + NewMedium);

}
 

for (var i = 0; i < NewMedium.length; i++) {

//console.log("i = " +NewMedium.length);

$("#selectboxname").multiselect("widget").find(":checkbox[value='"+ NewMedium[i]+"']").attr("checked", "checked");

$("#selectboxname option[value='"+ NewMedium[i]+"']").attr("selected", 1);

$("#selectboxname").multiselect("refresh");

//console.log(NewMedium[i]);

}