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:
<
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.