Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does something like jQuery.toggle(boolean) exist?

I write something similar to the following code a lot. It basically toggles an element based on some condition.

In the following made-up example, the condition is "If the agree checkbox is checked and the name field isn't empty".

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

I wish there was some sort of jQuery function that would work like this.

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

Is there something like this out there? Or are there other ways besides the first example to do this in a less if-else-ish way?

like image 846
jessegavin Avatar asked Mar 05 '10 17:03

jessegavin


People also ask

How do you toggle a Boolean?

To toggle a boolean, use the strict inequality (! ==) operator to compare the boolean to true , e.g. bool !== true . The comparison will return false if the boolean value is equal to true and vice versa, effectively toggling the boolean.

What is jQuery toggle?

Definition and Usage The toggle() method toggles between hide() and show() for the selected elements. This method checks the selected elements for visibility. show() is run if an element is hidden. hide() is run if an element is visible - This creates a toggle effect.

What can we use instead of in jQuery?

A progressive JavaScript framework, Vue. js is considered a good alternative to jQuery. It is an open-source, MVVM, front-end JS framework that is considered ideal to create user interfaces and single-page apps. It is also considered good for web interfaces, desktop, and mobile app development.


1 Answers

Ok, so I am an idiot and need to RTM before I ask 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); }); 
like image 55
jessegavin Avatar answered Sep 20 '22 15:09

jessegavin