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?
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.
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.
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.
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); });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With