views:

117

answers:

3

Ok, so I have:

function myfunc(foo,bar) {
    $('#div' + foo).hide();
    $('#div' + bar).show();
    return false;
}

Then I have:

function myOtherFunc() {
// define vars foo and bar
    myfunc(foo,bar);
}
var timerId = setInterval(myOtherFunc, 5000); // run myOtherFunc every 5 seconds.

which works fine. But the I have:

$('#myLink').click(function(){
// define vars 'foo' and 'bar'
myfunc(foo,bar);
return false;
});

Which doesn't work at all... What am I doing wrong?

A: 

Ok, it seems like the problem is in fact the variable definitions.

    var aa = $('.mydiv').attr('id'); // get current div's ID
var bb = aa.substring(6,7); // extract the number of the id, i.e. div1 will return '1'
var foo = bb;
var bar = foo + 1;

for some reason I get bar = "11" instead of "2" (or "21" instead of "3").

What am I doing wrong? Is there a better way to do this?

Adam
A: 

I believe it has something to do with the JavaScript handles type conversion. try parsing foo into an int. parseInt(foo, 10)

Jason
Thanks. Didn't work though...
Adam
A: 

Since bb will be of type String, foo will be a string, and Javascript will cast the value 1 into a string when you perform the + operator. You can simply change this to;

var aa = $('.mydiv').attr('id'); // get current div's ID
var bb = aa.substring(6,7); // extract the number of the id, i.e. div1 will return '1'
var foo = bb;
var bar = parseInt(foo) + 1;
Ed Schembor
var bar = 1 + foo; will also work.
Rob Van Dam
used var cc = parseInt(bb); Also works.
Adam