0

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?

2 Answers 2

3
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.

Sign up to request clarification or add additional context in comments.

Comments

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

1 Comment

@John: I added a radix to parseInt() (in case the .text() returned 09 for some reason). Other than that, +1.

Your Answer

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.