views:

37

answers:

3

Hi all, I've got the below code...

var ToggleButtons=new Array();
ToggleButtons[0] = "#Click";
ToggleButtons[1] = "#DoubleClick";
ToggleButtons[2] = "#Drag";
ToggleButtons[3] = "#RightClick";
ToggleButtons[4] = "#MiddleClick"; 


function SelectButton(id) {
    var x = 0;
    for (x = 0; x++; x < ToggleButtons.length) {
        if (x == id) {
            $(ToggleButtons[x]).addClass('ToggleButtonSelected');
        } else {
            $(ToggleButtons[x]).removeClass('ToggleButtonSelected');
        }
    }
} 

however, when I call SelectButton(n) with n=0->4, it hits the for() line and jumps straight to the closing brace.

on the for() line before it executes, Firebug shows (eg)

id=2
ToggleButtons.length=5
x=0

I've got the feeling I'm missing something obvious but I'm not sure what,

Many thanks

+4  A: 

Your for() order is mixed up, this:

for (x = 0; x++; x < ToggleButtons.length) {

Should be:

for (x = 0; x < ToggleButtons.length; x++) {

You can use .toggleClass("class", bool) to shorten it a bit though, like this:

function SelectButton(id) {
    for (var x = 0; x < ToggleButtons.length; x++) {
        $(ToggleButtons[x]).toggleClass('ToggleButtonSelected', x === id);
    }
} 

An even better approach would be to cache the selectors so they're not run each time, like this:

var ToggleButtons = [$("#Click"), $("#DoubleClick"), $("#Drag"), $("#RightClick"), $("#MiddleClick")]; 

function SelectButton(id) {
    $(".ToggleButtonSelected").removeClass('ToggleButtonSelected');
    ToggleButtons[id].addClass('ToggleButtonSelected');
} 
Nick Craver
+2  A: 

The parts of the for loop are the wrong way around, it should be initialisation, condition, then incrementation:

 for (x = 0; x < ToggleButtons.length; x++)
Douglas
Thank you - I've been staring at that for 10 minutes
Basiclife
+1  A: 

Change this line:

for (x = 0; x++; x < ToggleButtons.length) {

to this:

for (x = 0; x < ToggleButtons.length; x++) {
nickf
Damnit. TY. I awarded to Douglas as a) he needs it more and b) he explained his answer
Basiclife