-1

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

asked Sep 2, 2010 at 23:11

3 Answers 3

4

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');
} 
answered Sep 2, 2010 at 23:13
Sign up to request clarification or add additional context in comments.

Comments

2

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++)
answered Sep 2, 2010 at 23:14

1 Comment

Thank you - I've been staring at that for 10 minutes
1

Change this line:

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

to this:

for (x = 0; x < ToggleButtons.length; x++) {
answered Sep 2, 2010 at 23:14

1 Comment

Damnit. TY. I awarded to Douglas as a) he needs it more and b) he explained his answer

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.