Is there something like jQuery.toggle (boolean)?

I am writing something similar to the following code a lot. It basically switches the item based on some condition.

In the following prepared example, the condition is: "If the agree check box is agree , and the name field is not empty."

 $("button").click(function() { if ($("#agree").is(":checked") && $("#name").val() != "" ) { $("#mydiv").show(); } else { $("#mydiv").hide(); } }); 

I want some jQuery function to work like this.

 $("button").click(function() { var condition = $("#agree").is(":checked") && $("#name").val() != "" ); $("#mydiv").toggle(condition); }); 

Is there something similar? Or are there other ways than the first example to do this less than if-else-ish ?

+61
javascript jquery toggle
Mar 05 '10 at 17:30
source share
4 answers

Ok, so I'm an idiot and need RTM before asking questions.

jQuery.toggle () allows you to do this out of the box.

 $("button").click(function() { var condition = $("#agree").is(":checked") && $("#name").val() != "" ); $("#mydiv").toggle(condition); }); 
+79
Mar 05 '10 at 18:03
source share

First, let's see if I understand what you want to do correctly ... You want to look at the state of the checkbox (checked or not) and hide or show the second div based on the state of this value.

Define this style:

 .noDisplay { display:none; } 

Use this javascript:

 $("button").click(function() { $("#mydiv").toggleClass("noDisplay", $("#name").val() == ""); }); 

The jQuery documentation can be found here: http://api.jquery.com/toggleClass/

+8
05 Mar '10 at 17:38
source share

You can write the function yourself.

 function toggleIf(element, condition) { if (condition) { element.show(); } else { element.hide(); } } 

Then use it as follows:

 toggleIf($("button"), $("#agree").is(":checked") && $("#name").val() != ""); 
+5
Mar 05 '10 at 17:33
source share

If toggle() not suitable for you (for example, because it is animating), you can write a small jQuery plugin, for example:

 $.fn.toggleIf = function(showOrHide) { return this.each(function() { if (showOrHide) { return $(this).show(); } else { return $(this).hide(); } }); }; 

and then use it like this:

 $(element).toggleIf(condition); 
-one
Apr 28 '13 at 16:54
source share



All Articles