/** * A simple solution to the “other” * problem with select boxes. * * @author John-David Dalton * @link http://ajaxian.com/archives/a-simple-solution-to-the-other-problem-with-select-boxes#comments */ // Attempt 1) execute code when dom is loaded document.observe('dom:loaded', function() { $$('select.leader').invoke('change', function() { if ($F(this) === 'other') { this.next().writeAttribute('name', this.readAttribute('name')).show() } else this.next().removeAttribute('name').hide(); }); }); // Attempt 2) OR if you include effects.js // ... $$('select.leader').invoke('change', function() { var options = { duration:0.5 }; if ($F(this) === 'other') { this.next().writeAttribute('name', this.readAttribute('name')).appear(options) } else this.next().removeAttribute('name').fade(options); }); // ... // Attempt 3) OR if you want to call the handler after creating the observer // ... function onChange() { if ($F(this) === 'other') { this.next().writeAttribute('name', this.readAttribute('name')).show() } else this.next().removeAttribute('name').hide(); } $$('select.leader').each(function(element) { element.observe('change', onChange); onChange.bind(element)(); }); // ... // Attempt 4) OR adding some sugar Element.addMethods({ fire: Event.fire.wrap(function(proceed, element, eventName, memo) { element = $(element); var w, event, eventID; $w(eventName)._each(function(name) { // use original "fire" if it's a custom:event if (name.include(':')) return proceed(element, name, memo); // handle native events eventID = (element._prototypeEventID || [null])[0]; if (!eventID || !(w = Event.cache[eventID][name])) return false; // poor man's event object event = Event.extend({ }); event.eventName = name; event.memo = memo || { }; // execute event wrappers w._each(function(wrapper) { wrapper(event) }); }); return element; }) }); document.observe('dom:loaded', function() { $$('select.leader').invoke('change', function() { if ($F(this) === 'other') { this.next().writeAttribute('name', this.readAttribute('name')).show() } else this.next().removeAttribute('name').hide(); }).invoke('fire', 'change'); });