Going to be very hard to explain this without hundreds of lines of code but I will try!
I have a parent object which contains an array of children objects. The parent writes a MULTIPLE select element to a page using this function
function writecollectionmultiselect(name,displayname,selectedrange){
// Create select page element
var collection = $("<select/>");
collection.attr("name",name);
collection.attr("MULTIPLE","multiple");
// Loop over elements in this collection and ask them to draw themselves
for(var i=0; i<this.objectarray.length;i++){
collection.append(this.objectarray[i].writemultioption(selectedrange));
}
return collection;
}
The parent asks each child to draw its own option element depending on whether their id is in the ‘selectedrange’
function writemultioption(selectedrange){
var option = $("<option/>");
option.val(this.data.id);
option.html(this.data.name);
if(selectedrange.indexOf(parseInt(this.data.id)) >= 0){
option.attr('selected', 'selected');
}
return option;
}
This works fine when selectedrange is provided as selectedrange=[1,2,3]
However if I read the selected values of the page element using jquery
selectedrange = $('[name='+myname+"]").val();
when I try to call the first function the indexOf function seems to completely fall over. I added this line of debug code
alert("looking for "+this.data.id+" in "+selectedrange+" result "+selectedrange.indexOf(parseInt(this.data.id)))
When I first draw the selector I get this:
looking for 1 in 1,2,3 result 0
However, reading the value and redrawing gives
looking for 1 in 1,2,3 result -1
I suspect some sort of data type issue but hvae been banging my head against this for hours. Any help appreciated.
jQuery will give you an array of strings, and you are converting the
this.data.idto a number usingparseIntso they will never match, because theindexOfcomparison is strict.One solution is to convert the array of strings to numbers.
Or another solution is to keep the array as strings, but get rid of the
parseIntand just do this.