Showing and hiding objects in jQuery

I would like to show and hide objects (divs, texts or btns) according to some conditions.

In C #, we can write to reduce the number of encodings:

txtA.visible = (type == "A");
txtB.visible = (type == "B");
txtC.visible = (type == "C");

In jQuery, to show and hide, I use the .show () and .hide () methods. But I have to write a lot of lines for this simple function. For instance,

if (type == "A")
   $("#txtA").show();
else
   $("#txtA").hide();

if (type == "B")
   $("#txtB").show();
else
   $("#txtB").hide();

if (type == "C")
   $("#txtC").show();
else
   $("#txtC").hide();

In any case, to achieve the same functionality with fewer lines? Thank.

+3
source share
4 answers

.toggle(showOrHide) Allows a logical to show or hide an element.

You can rewrite your example like this:

$("#txtA").toggle(type === "A");
$("#txtB").toggle(type === "B");
$("#txtC").toggle(type === "C");

Jsfiddle example

+10
source

Use the ternary operator:

(type == "A") ? $("#txtA").show() : $("#txtA").hide();
+6
source
+1

( , )

// Remember ids are case sensitive
var type = 'A';

$('#txt' + type).show() // Show the current type
  .siblings().hide();  // Hide all other elements

Fiddle: http://jsfiddle.net/garreh/4JkGm/

If your sibling elements are not always the type you want to hide, just mark the filter on it:

$('#txt' + type)
  .show() // Show the current type
  .siblings()
  .filter(function() {
      return (this.id.match(/^txt[A-C]$/))
  }).hide(); // Hide all other elements

Fiddle: http://jsfiddle.net/garreh/4JkGm/1/

+1
source

All Articles