views:

44

answers:

3

Hi

I have this

 var selected = []
        $('#SelectBoxContainer .DDLs :selected').each(function (i, selected)
        {
            alert($(selected).val());
            selected[i] = $(selected).val();
        });

My alert is telling me that it is going through this loop and getting the select box values. Yet once everything is said and done there is nothing in my "selected" array.

A: 

you are opening and closing array and then doing some magic without result...

it's late, but var selected = [] $('#SelectBoxContainer .DDLs :selected').each <..code....> has no result really.

try making array and then: selected.put($('#SelectBoxContainer ))

in other words, you don't have ';' after 'var selected = []'

fazo
what is that?.. the OP says it alerted the values... `;` is not really the problem...
Reigel
by some ackward way it doesn't state of 'missing ;' while it does if next line starts after []. we have syntax for a reason
fazo
Javascript (**unfortunately**) does not require `;`'s.
deceze
in Javascript, `;` are not necessary in some situations. But it's a good practice to put it.
Reigel
+5  A: 

Your callback defines a local variable named selected, which hides the selected variable in the outer scope. The selected in selected[i] = is the selected from function (i, selected), not the selected from var selected.

Rename one of the two variables for this to work.

deceze
bingo! I did not thought about that! +1
Reigel
I did not even notice that. I can see why it does not work now.
chobo2
A: 

How do you expect to work with two variables named "selected" at the same time? Change the name of your function's second parameter so that it doesn't shadow the array you're trying to write to:

var selected = [];
$('#SelectBoxContainer .DDLs :selected').each(function (i, item)
{
    selected[i] = $(item).val();
});

You can also use the array push method instead of bothering with indices:

selected.push( $(item).val() )
hobbs
I think the `indices` are meant to be there for the OP. I guess.. Because from time to time `:selected` will not have the same indices.. :) Just my guess..
Reigel
@Reigel No, the `i` is a loop index, always beginning at 0, always incrementing by 1 with each iteration.
deceze
@deceze Oh?! I thought that it's the index of the current element... my bad then..
Reigel