views:

1337

answers:

2

Is there a way I can generate switch statements in jquery/javascript by using some sort of loop to do the work for me? For example, if I had a statement like:

switch ($("#play option:selected").text()) {
    case '1':
        $("#play_1").slideDown().find("input").addClass("someClass");
        break;
    case '2':
        $("#play_1").slideDown().find("input").addClass("someClass");
        $("#play_2").slideDown().find("input").addClass("someClass");
        break;
}

This is fine if I only have a few options in my select menu, but what I had 99 options and therefore by case '99' I had to display 99 new divs or whatever they might be?

+3  A: 
for (var i = 1; i <= $("#play option:selected").text(); ++i) {
    $("#play_"+i).slideDown().find("input").addClass("someClass");
}

If you select 10 that loop will find the ten elements from #play_1 to #play_10 and animate them.

John Kugelman
+1  A: 
for (var i = 1; i <= parseInt($("#play option:selected").text(), 10); i++) {
    $("#play_" + i).slideDown().find("input").addClass("someClass");
}
John Rasch
@John: I added a radix to `parseInt()` (in case the `.text()` returned `09` for some reason). Other than that, +1.
Grant Wagner