8bitcat
8bitcat

Reputation: 2234

javascript for loop with decimals

I'm trying to use this for loop in order to show divs. But I get a strange error from the jQuery lib.

Error: Syntax error, unrecognized expression: =10]

I have read about the problems with javascript decimals, but I still can't understand why this won't work:

for (var i = 10.00; i >= ui.value; i -= 0.25) {
    $("data_id=" + Math.floor(i) + "]").show();
}

When hiding the divs, I use this and it works fine:

for (var i = 0.00; i < ui.value; i += 0.25) {
    $("[data_id=" + Math.floor(i) + "]").hide();
}

Upvotes: 5

Views: 3711

Answers (4)

nbrooks
nbrooks

Reputation: 18233

You're missing your opening square bracket for the attribute equals selector:

for (var i = 10.00; i >= ui.value; i -= 0.25) {
    $("[data_id=" + Math.floor(i) + "]").show();
}


As others have mentioned, however, there is absolutely no reason to be using floats for this, since the call to .floor() essentially means you are calling .show() on each of the divs 4 times unnecessarily:

for (var i = 10; i >= ui.value; i--) {
    $("[data_id=" + i + "]").show();
}

This should accomplish exactly you want, in about a quarter of the work.

Upvotes: 2

Can Poyrazoğlu
Can Poyrazoğlu

Reputation: 34790

You should never, ever rely on floating point arithmetic for iteration/indexing variables. They may run you into strange situations, and even worse, different processors handle floating points differently. Your example doesn't seem to have any side-effects of floating points, but using floating points is really a bad practice.

Upvotes: 1

Christofer Eliasson
Christofer Eliasson

Reputation: 33865

You are missing a [ in your selector here:

$("data_id=" + Math.floor(i) + "]").show();

Which should be:

$("[data_id=" + Math.floor(i) + "]").show();

You should probably add ' around the value of data_id as well, so the final result should be:

$("[data_id='" + Math.floor(i) + "']").show();

Upvotes: 1

Gregor
Gregor

Reputation: 4434

You forgot the [ in the first loop, this will work:

for (var i = 10.00; i >= ui.value; i -= 0.25) {
    $("[data_id=" + Math.floor(i) + "]").show();
}

You should transform this into an integer loop, if you are .floor()-ing the numbers, anyway.

Upvotes: 7

Related Questions