Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

toggle form input states in javascript

I know how to toggle (active/disabled or visible/hidden) html form input fields with JavaScript.

But if there are several input fields, I guess it is better to use a declarative solution. I mean a solution without coding methods which use long "if ... else ..." statements.

Simple example:

The customer can enter if he likes long distance running. If he enables this, an other input gets visible: "What is your preferred running distance?"

I can code (and have done many times) "if ... show ....", but I am not a JS expert.

How could this be done declarative in JS?

http://en.wikipedia.org/wiki/Declarative_programming:

In computer science, declarative programming is a programming paradigm, a style of building the structure and elements of computer programs, that expresses the logic of a computation without describing its control flow.

like image 281
guettli Avatar asked Dec 06 '25 14:12

guettli


1 Answers

I use this extension function (from this answer):

(function($) {
    $.fn.toggleDisabled = function(){
        return this.each(function(){
            this.disabled = !this.disabled;
        });
    };
})(jQuery);

You can do something like this:

$(".long-distance-running-checkbox").change(function(){
  $(".long-distance-running-related").toggleDisabled();
}
like image 97
Max Al Farakh Avatar answered Dec 08 '25 07:12

Max Al Farakh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!