Related Posts

Archive

Hide form sections in Prototype: “.display-switch”

October 22nd, 2008

I had an issue with some rather complex forms I was making - There were times that I wanted to hide multiple sections of a form based on the selection of radio button or select drop-down.

As both of these have only one active option… well, I wanted to hide all other options.

The following code (dependent on prototype 1.6.x) does just this. Hopefully I’ll be able to explain it better soon.

$(document).observe("dom:loaded", function() {
/* generic show/hide section function */
activate_display_switch();
}
 
 
/* a select/input with class of display-switch will show() all classes with currently selected value (select_name)_(value), and hide() others */
function activate_display_switch() {
var signal = Prototype.Browser.IE ? 'focus' : 'change';
$$('select.display-switch').invoke('observe','change', function(){
var x = this;
x.childElements().each(function(y){ x.up('form').select("." + x.id + "_" + y.value).invoke('hide'); });
x.up('form').select("." + x.id + "_" + x.value).invoke('show');
});
$$('input.display-switch').invoke('observe',signal, function(){
var x = this;
switch(x.type.toUpperCase()) {
case "RADIO":
x.up('form').descendants().collect( function(s) { if (s.tagName.toUpperCase() == "INPUT" && s.type.toUpperCase() == "RADIO" && s.name == x.name ) return s; }).compact().each(function(y){ x.up('form').select('.' + y.id + "_" + y.value).invoke('hide'); });
x.up('form').select("." + x.id + "_" + x.value).invoke('show');
break;
default:
alert("Display Switch unimplemented for " + x.tagName + "[" + x.type.toUpperCase() + "], ” + x.id);
break;
}
});
}

Posted in JavaScript |

Comments are closed.

Previous post: Being nice to Windows in a Dual Boot Setup

Next Post: Rails and Normalizing Phone Numbers