Sudhanshu Saini Sudhanshu Saini - 4 months ago 11
jQuery Question

Simple switch case not working

Here is simple code to change the display of a div on the button action using switch case.
Please have a look at it i am not getting where i went wrong.

Link: https://jsfiddle.net/r6nkuwvc/

javascipt code:

$(document).on('click', ".change", function() {
var $input = $(this);
$(".same").each(function() {
if ($(this).css("display") == "block") {
$(this).css("display", "none");
}
});
switch ($input.attr("id")) {
case "b1":
$("#abc").css("display", "block");
break;
case "b2":
$("#xyz").css("display", "block");
break;
}
});

Answer

As has been pointed out in the comments, your code works as is. You just forgot to add the jQuery library, and the selectors #hello and #bye didn't exist. Next to that, you are also over-complicating your code. In jQuery you do not have to check if an element is visible before hiding it, you can just hide it. And when using a class selector you do not have to run .each against it for jQuery's own internal functions such as hide(); jQuery will hide all elements with this class.

https://jsfiddle.net/r6nkuwvc/5/

$(document).on('click', ".change", function() {
  $(".same").hide();

  switch ($(this).attr("id")) {
    case "b1":
      $("#abc").show();
      break;
    case "b2":
      $("#xyz").show();
      break;
  }
});
Comments