-2

I want to use switch condition in JavaScript code. but i dont know how? please help me to do this.. thanks in advance

2

4 Answers 4

6
switch(n)
{
case 1:
  execute code block 1
  break;
case 2:
  execute code block 2
  break;
default:
  code to be executed if n is different from case 1 and 2
}

http://www.w3schools.com/js/js_switch.asp

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

Comments

1

You don't have a lot of detail in your question but I'll try to help regardless - but without knowing the full scenario its a bit hard to give you a definitive answer.

I'm going to assume you want to handle a redirection on a button click, but with some conditions?

Usually you would use a simple case statement to handle this (or an if/else if there is only two conditions), such as the following (using jQuery for event bindings):

<button id="button1">Button 1</button>
<button id="button2">Button 2</button>

<script type="text/javascript">
  jQuery(function() {
    jQuery("button1, button2").click(function(e) {
      switch(jQuery(this).attr("id")) {
        case "button1":
          location.href = "http://clickedonbutton1.com";
          break;
        case "button2":
          location.href = "http://clickedonbutton2.com";
          break;
       default:
          alert("Dont know what happened here....");
      }
    });
  });
</script>

Comments

1

Read switch

  1. No restriction on case value type.

  2. You can use "string" case value in JavaScript

  3. You can add duplicate case value. The first matching case value is recognized, regardless of duplicates.

Comments

-1
switch(youVariable)
{
   case "test1":
   break;

   case "test2":
   break;

   default:
   break;

}

1 Comment

It's not the same. You can't use strings in switch statements in C++.

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.