How to use jQuery to show/hide divs based on radio button selection?

后端 未结 8 690
暗喜
暗喜 2020-11-30 05:38

I have some radio buttons and I\'d like to have different hidden divs show up based on which radio button is selected. Here\'s what the HTML looks like:

<         


        
8条回答
  •  一整个雨季
    2020-11-30 06:08

    An interesting solution is to make this declarative: you just give every div that should be shown an attribute automaticallyVisibleIfIdChecked with the id of the checkbox or radio button on which it depends. That is, your form looks like this:

    ....
    lorem ipsum dolor
    consectetur adipisicing

    and have some page independent JavaScript that nicely uses functional programming:

    function executeAutomaticVisibility(name) {
        $("[name="+name+"]:checked").each(function() {
            $("[automaticallyVisibleIfIdChecked=" + this.id+"]").show();
        });
        $("[name="+name+"]:not(:checked)").each(function() {
            $("[automaticallyVisibleIfIdChecked=" + this.id+"]").hide();
        });
    }
    
    $(document).ready( function() {
        triggers = $("[automaticallyVisibleIfIdChecked]")
            .map(function(){ return $("#" + $(this).attr("automaticallyVisibleIfIdChecked")).get() })
        $.unique(triggers);
        triggers.each( function() {
            executeAutomaticVisibility(this.name);
            $(this).change( function(){ executeAutomaticVisibility(this.name); } );
        });
    });
    

    Similarily you could automatically enable / disable form fields with an attribute automaticallyEnabledIfChecked.

    I think this method is nice since it avoids having to create specific JavaScript for your page - you just insert some attributes that say what should be done.

提交回复
热议问题